Java GregorianCalendar Timezone
Asked Answered
B

4

6

I have a weird problem with a Java Gregorian Calendar:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S Z");
sdf.setTimeZone(TimeZone.getTimeZone("US/Pacific"));

GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("US/Pacific"));
cal1.setTimeInMillis(1320566400000L);

GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("US/Pacific"));
cal2.setTimeInMillis(1320570000000L);

System.out.println(sdf.format(cal1.getTime()));
System.out.println(sdf.format(cal2.getTime())); 

I executed the above given code on a machine with default timezone = US Pacific, but the machine is running in Germany.

The result is the following:

2011-11-06 01:00:00:0 -0700
2011-11-06 01:00:00:0 -0800

I really do not understand, why there is a different time zone in the result... I also tested the code on another machine (default Timezone = GMT) and it works correct.

Do somebody have an idea, why this problem occurs?

Best, Michael

Bedell answered 14/6, 2012 at 10:42 Comment(1)
Wich version of Java did you use? ;-) Sometimes there are bugs in one version and not in the others.Reins
M
6

Add these lines to your program:

for (int i=0; i<24; i++) {
    cal1.add(Calendar.MINUTE, i*5);
    System.out.println(" : " + sdf.format(cal1.getTime()));
}

And you'll see:

 : 2011-11-06 01:00:00:0 -0700
 : 2011-11-06 01:05:00:0 -0700
 : 2011-11-06 01:15:00:0 -0700
 : 2011-11-06 01:30:00:0 -0700
 : 2011-11-06 01:50:00:0 -0700
 : 2011-11-06 01:15:00:0 -0800
 : 2011-11-06 01:45:00:0 -0800
 : 2011-11-06 02:20:00:0 -0800
 : 2011-11-06 03:00:00:0 -0800

So it seems you're changing summer time to winter time. My timezone is CET (UTC+01:00), so I can't tell why it's working on your second machine.

Mannie answered 14/6, 2012 at 10:51 Comment(1)
Thanks for the info with the daylight saving time. In Germany the change of the daylight saving time is one week later - therefore I didn't thought about it :)Bedell
A
2

November 6, 2011 was when daylight savings time ended in the US. So what you're seeing is the clock hit 2am on Nov 6th and then it rolls back to 1am to fall back an hour to standard time. So the offset also changes from -7 to -8 from GMT I believe for Pacific time. So it is working correctly from what I can see.

Asshur answered 14/6, 2012 at 12:44 Comment(0)
A
1

I would advice you to use Gregorian chronology in Joda-Time

Accelerate answered 14/6, 2012 at 10:46 Comment(0)
A
0

Please check in your control panel that you have not activated Summer's time. This bug may be because of this

Agc answered 14/6, 2012 at 12:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.