开发者

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 p开发者_如何学JAVAass 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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜