Search code examples
javajava.util.calendar

Set time to 00:00:00


I have a problem resetting hours in Java. For a given date I want to set the hours to 00:00:00.

This is my code :

/**
     * Resets milliseconds, seconds, minutes and hours from the provided date
     *
     * @param date
     * @return
     */
    public static Date trim(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR, 0);

        return calendar.getTime();
    }

The problem is that sometimes the time is 12:00:00 and sometimes it is 00:00:00 and when I query the database for an entity that was saved on 07.02.2013 00:00:00 and the actual entity time, that is stored, is 12:00:00 the query fails.

I know that 12:00:00 == 00:00:00!

I am using AppEngine. Is this an appengine bug, problem or some other issue? Or does it depend on something else?


Solution

  • Use another constant instead of Calendar.HOUR, use Calendar.HOUR_OF_DAY.

    calendar.set(Calendar.HOUR_OF_DAY, 0);
    

    Calendar.HOUR uses 0-11 (for use with AM/PM), and Calendar.HOUR_OF_DAY uses 0-23.

    To quote the Javadocs:

    public static final int 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.

    and

    public static final int 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.

    Testing ("now" is currently c. 14:55 on July 23, 2013 Pacific Daylight Time):

    public class Main
    {
       static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
        public static void main(String[] args)
        {
            Calendar now = Calendar.getInstance();
            now.set(Calendar.HOUR, 0);
            now.set(Calendar.MINUTE, 0);
            now.set(Calendar.SECOND, 0);
            System.out.println(sdf.format(now.getTime()));
            now.set(Calendar.HOUR_OF_DAY, 0);
            System.out.println(sdf.format(now.getTime()));
        }
    }
    

    Output:

    $ javac Main.java
    $ java Main
    2013-07-23 12:00:00
    2013-07-23 00:00:00