Matjaz Matjaz - 11 months ago 43
Java Question

java GregorianCalendar adding hour strange behavior

I have a problem with GregorianCalendar so if you please can help me out with it. First I'll give you my code:

private String changeClock(String day, String clock, int change) {
String time="";
DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm");
try {
Date d=df.parse(day+" "+clock);
GregorianCalendar g=new GregorianCalendar();
g.add(GregorianCalendar.HOUR_OF_DAY, change);
+g.get(GregorianCalendar.DAY_OF_MONTH)+" "
} catch (Exception e) {
return time;

Let me explain what is happening. I have a GUI with + and - button. When someone press + it add one hour, or if - is pressed then take one hour.

Now example, time is 23:00 and I press +, it is everything ok and it jumps to 00:00 of the next day. Problems are on 12:00. If it is 12:00 and I press + it goes to 1:00 and that goes on and on. It doesn't move to the next day even after 2x12 hours or 21465x12 hours.
Moving backward is a little better if I can say so. When it is 00:00 and I press - it changes to yesterday 23:00 (also date changes). If I then press + it changes also one day forward (so to today in this case).

What have I done wrong or what more should I write to my code?

Thanks for your help guys.

Answer Source

Your date format is wrong...

You're using hh, which is a representation of the "Hour in am/pm (1-12)", so a time of 1pm is been converted to 1am instead.

You should be using HH which is a a representation of the "Hour in day (0-23)".

Either that, or you need supply a date/time format with the am/pm marker...

Using either DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm"); or DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm a");

Instead of relying on String date/time values, you should be passing in and back a Date object, leave the formatting for the display.