I am running into a strange issue with Java Calendar.
The following code adds 3 hours consecutively from a date starting at midnight.
public static void main(String[] args) {
Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
// Setting to January 29th, 1920 at 00:00:00
// now.setTimeZone(TimeZone.getTimeZone("GMT+0"));
now.set(Calendar.YEAR, 1920);
now.set(Calendar.MONTH, 0);
now.set(Calendar.DAY_OF_MONTH, 29);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
now.setLenient(false);
int threeHours = 1000 * 60 * 60 * 3;
SimpleDateFormat sdf
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
for (int i=0;i<25;i++) {
System.out.println(sdf.format(now.getTime()));
now.add(Calendar.MILLISECOND, threeHours);
}
}
Yet, the displayed result is:
1920-01-29 01:00:00 000
1920-01-29 04:00:00 000
1920-01-29 07:00:00 000
1920-01-29 10:00:00 000
1920-01-29 13:00:00 000
1920-01-29 16:00:00 000
1920-01-29 19:00:00 000
1920-01-29 22:00:00 000
1920-01-30 01:00:00 000
1920-01-30 04:00:00 000
1920-01-30 07:00:00 000
1920-01-30 10:00:00 000
1920-01-30 13:00:00 000
1920-01-30 16:00:00 000
1920-01-30 19:00:00 000
1920-01-30 22:00:00 000
1920-01-31 01:00:00 000
1920-01-31 04:00:00 000
1920-01-31 07:00:00 000
1920-01-31 10:00:00 000
1920-01-31 13:00:00 000
1920-01-31 16:00:00 000
1920-01-31 19:00:00 000
1920-01-31 22:00:00 000
1920-02-01 01:00:00 000
Why is the first hour 1 and not 0? I am located at GMT+1, could this be related?
Using now.getTime()
gets the Date
which doesn't have a time zone.
Try setting the timezone with
sdf.setTimeZone(now.getTimeZone());
i guess you should use now.set(Calendar.HOUR, 0); instead now.set(Calendar.HOUR_OF_DAY, 0);
now it should work fine
Calendar now = Calendar.getInstance();
TimeZone timezone = TimeZone.getTimeZone("GMT+0");
now.set(Calendar.YEAR, 1920);
now.set(Calendar.MONTH, 0);
now.set(Calendar.DAY_OF_MONTH, 29);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
now.setLenient(false);
int threeHours = 1000 * 60 * 60 * 3;
SimpleDateFormat sdf
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
sdf.setTimeZone(timezone);
for (int i=0;i<25;i++) {
System.out.println(sdf.format(now.getTime()));
now.add(Calendar.MILLISECOND, threeHours);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With