Search code examples
grailsgroovygregorian-calendar

Issue with adding hours to Gregorian Calendar


I have a Grails application I created a Gregorian Calendar GMT date. The time of day was 11:00:00 PM GMT. I added 3 hours to the Gregorian Calendar object and it changed the time of day to 2:00:00 AM but it did not increment the day of the year. I had to check for the case when I add hours to the calender and if that new time should pass to a new day I had to increment the day of the year. This seems like a bug in the GregorianCalendar class but want to make sure I wasn't doing something wrong. Here are the different ways I added hours.

myCalender.add(Calender.HOUR,3)

and

myCalender.add(Calender.HOUR_OF_DAY,3)`

and

myCalender.setTimeInMillis( myCalender.getTimeInMillis() + (( (1000 * 60) * 60) * 3))`

If the begin date and time is for example 6/1/2011 11:00:00 PM GMT and I execute the above code, I would expect the new date and time to be 6/2/2011 02:00:00 AM GMT but what I got was 6/1/2011 02:00:00 AM GMT. Can someone please educate me?


Solution

  • Works for me:

    final DateFormat format = SimpleDateFormat.getDateTimeInstance();
    format.setTimeZone(DateUtils.UTC_TIME_ZONE);
    
    final GregorianCalendar cal = new GregorianCalendar(DateUtils.UTC_TIME_ZONE);
    cal.set(2011, Calendar.JUNE, 1, 23, 30, 0);
    System.out.println(format.format(cal.getTime()));
    cal.add(Calendar.HOUR_OF_DAY, 1);
    System.out.println(format.format(cal.getTime()));
    

    Produces:

    2011-06-01 23:30:00
    2011-06-02 00:30:00