Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GregorianCalendar / Calendar and setting the HOUR field oddity

I'm trying to create a 'fixed' time (midnight in 24 hour clock format, i.e., 00:00:00) to set as a string for a SQL SELECT query using the the following...

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

GregorianCalendar todayDate = new GregorianCalendar();
Log.d(TAG, "todayDate: " + todayDate.getTime().toString());
Log.d(TAG, "formatted todayDate: " + sdf.format(todayDate.getTime()));
todayDate.clear(Calendar.HOUR);
todayDate.clear(Calendar.MINUTE);
todayDate.clear(Calendar.SECOND);
todayDate.set(Calendar.HOUR, 0);
todayDate.set(Calendar.MINUTE, 0);
todayDate.set(Calendar.SECOND, 0);
Log.d(TAG, "formatted modified todayDate: " + sdf.format(todayDate.getTime()));

This is fine UNLESS the current time is PM. For example,

todayDate: Fri Jan 28 23:34:34 GMT 2011
formatted todayDate: 2011-01-28 23:34:34
formatted modified todayDate: 2011-01-28 12:00:00 <- THE hour is 12 not 00

If I do this when the current time is between midnight and midday, (i.e., 00:00:00 -> 11:59:59 AM) then my hour in the formatted string is correctly set to 00. If I do it at any time after midday and before midnight then I get 12 for my hour and not 00.

Can anybody explain this and help me find a fix (or alternative way of doing things) please?

like image 382
Squonk Avatar asked Jan 28 '11 00:01

Squonk


1 Answers

You need to set HOUR_OF_DAY to 0 instead of HOUR

todayDate.set(Calendar.HOUR_OF_DAY, 0);

From the API docs:

HOUR Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.

HOUR_OF_DAY Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.

like image 150
armandino Avatar answered Sep 24 '22 08:09

armandino