Strange problem with timezone, calendar and SimpleDateFormat

Consider the following code:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.US); long start = sdf.parse("10:30:00 30/09/2009").getTime(); long end = sdf.parse("10:30:00 30/10/2009").getTime(); Calendar c = Calendar.getInstance(Locale.US); c.setTimeInMillis(start); System.out.println("Start = " + c.getTime()); c.setTimeInMillis(end); System.out.println(" End = " + c.getTime()); 

When I run this piece of code, I have the following output:

 Start = Wed Sep 30 10:30:00 CEST 2009 End = Fri Oct 30 10:30:00 CET 2009 

Why am I getting a different time zone?

Please note that if I set the first date in August and the second in September, the output will display the same time zone in both cases:

 long start = sdf.parse("10:30:00 30/08/2009").getTime(); long end = sdf.parse("10:30:00 30/09/2009").getTime(); 

will display:

 Start = Sun Aug 30 10:30:00 CEST 2009 End = Wed Sep 30 10:30:00 CEST 2009 

I am using Java 1.6.0_14

+7
java date calendar simpledateformat
source share
3 answers

CEST - Central European Summer Time. This is the same as the CET with summer savings.

+9
source share

You can set the default time zone

  import java.util.TimeZone; ... TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // or "Etc/GMT-1" SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.US); long start = sdf.parse("10:30:00 30/09/2009").getTime(); long end = sdf.parse("10:30:00 30/10/2009").getTime(); Calendar c = Calendar.getInstance(Locale.US); c.setTimeInMillis(start); System.out.println("Start = " + c.getTime()); c.setTimeInMillis(end); System.out.println(" End = " + c.getTime()); 

use TimeZone.getAvailableIDs() to view all available identifiers.

EDIT : you can also use the new SimpleTimeZone

  TimeZone.setDefault(new SimpleTimeZone(60 * 60 * 1000, "CET")); 
+6
source share

Yes, this is due to summer time. If you use a time zone that recognizes DST, it will be automatically used. You can use GMT, for example, if you do not want it.

0
source share

All Articles