Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hours corrupted when subtract one day from GregorianCalendar

Tags:

java

datetime

I use the following code:

Calendar calendar = new GregorianCalendar(0,0,0);
calendar.set(Calendar.YEAR, 1942);
calendar.set(Calendar.MONTH, 3);
calendar.set(Calendar.DAY_OF_MONTH, 4);

Date date1 = calendar.getTime();

calendar.add(Calendar.DAY_OF_MONTH, -1);

Date date2 = calendar.getTime();

System.out.println(date1 + "\n" + date2);

This code output follows:

Sat Apr 04 00:00:00 EEST 1942
Fri Apr 03 01:00:00 EEST 1942

Actually I subtract 1 day and time should be preserved. But why second line of output contains 1 hour in the time while it should be 0?

EDIT:

Currently I am testing my code in Europe/Helsinki timezone.

like image 239
sergtk Avatar asked Oct 18 '09 21:10

sergtk


2 Answers

I suppose you are using a Finnish timezone. In Finland, daylight saving time was introduced in 1942 by adjusting the clock from April 2nd, 23:59:59 to April 3rd, 1:00:00. The time span April 3rd, 0:00:00 to 0:59:59 did not exist, so the Java Calendar makes a best effort result.

like image 125
jarnbjo Avatar answered Nov 15 '22 06:11

jarnbjo


Are you using the latest java-version? Check that, because on my java installation (1.6.0_16) it works fine, output is:

Sat Apr 04 00:00:00 GMT 1942
Fri Apr 03 00:00:00 GMT 1942

Sun usually update the time-zone-database on the java-updates, so check you are using the latest version!

Or, other thing:

Perhaps it has something to do with daylight saving? The US government introduced Daylight Saving in the WWII-years, this could be the cause in your timezone but not in mine?

like image 23
theomega Avatar answered Nov 15 '22 05:11

theomega