Reputation: 12047
Below is code that I am using to move a date back a 3 hours. It displays the new time and also am pm value. But when it gets to 12pm or am it changes the am pm value of the new time to the same as the 12 it came from. Ie if it is set at 12am and the new value is 9pm it outputs 9pm. Am I missing something simple? Am I thinking about this correctly that 12am is midnight as the such?
calendar.set(Calendar.HOUR, HourValue);
calendar.set(Calendar.MINUTE, MinValue);
calendar.set(Calendar.SECOND, 0);
if(AMPM.equals("AM")){ampmval=0;}
else{ampmval=1;}
Log.e("AMPMVAL Before",Integer.toString(ampmval));
sdf = new SimpleDateFormat("hh");
NewHourValue = sdf.format(calendar.getTime());
Log.e("Before Time",NewHourValue);
calendar.set(Calendar.AM_PM, ampmval);
calendar.add(Calendar.MINUTE, -300);
int AmOrPm = calendar.get(Calendar.AM_PM);
Log.e("AMPMVAL After",Integer.toString(AmOrPm));
sdf = new SimpleDateFormat("hh");
NewHourValue = sdf.format(calendar.getTime());
Log.e("After Time",NewHourValue);
This outputs something like
05-15 23:07:11.233: E/Before Time(457): 09:00:00 PM
05-15 23:07:11.240: E/AMPMVAL After(457): 0
05-15 23:07:11.640: E/After Time(457): 06:00:00 AM
05-15 23:07:23.369: E/AMPMVAL Before(457):0
05-15 23:07:23.742: E/Before Time(457): 10:00:00 PM
05-15 23:07:23.749: E/AMPMVAL After(457): 0
05-15 23:07:24.113: E/After Time(457): 07:00:00 AM
05-15 23:07:28.320: E/AMPMVAL Before(457):0
05-15 23:07:28.712: E/Before Time(457): 11:00:00 PM
05-15 23:07:28.720: E/AMPMVAL After(457): 0
05-15 23:07:29.112: E/After Time(457): 08:00:00 AM
05-15 23:07:34.700: E/AMPMVAL Before(457):1
05-15 23:07:35.300: E/Before Time(457): 12:00:00 AM
05-15 23:07:35.330: E/AMPMVAL After(457): 1
05-15 23:07:35.693: E/After Time(457): 09:00:00 PM
As you can see it works fine as I increment through the hours before 12am (Midnight) but when it gets to midnight it then says that the new value is also in am
Upvotes: 3
Views: 3179
Reputation: 116
Just set hour to 0. Everything else can remain the same and it will work fine. In the Java Calendar api, it is even said that "Noon and midnight are represented by 0, not by 12"
Upvotes: 0
Reputation: 733
I would suggest to show exact hour string in Calendar Object initialize df object as given below::
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Then the date string 2012-05-19 12:00:00 when converted to Calendar object will have Hour as 12 not 0.
But of your are using Date Format as
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
then 12 will be converted to 0 in hour
Upvotes: 1
Reputation: 541
What HOUR value you use for midnight/noon? 0 and 12 are not same.
E.g for midnight you have to set AM_PM
to AM
and HOUR
to 0 (not 12). DateFormat
output in AM/PM format will show 12 AM on midnight.
Upvotes: 2