Strange problem with timezone, calendar and SimpleDateFormat

19,820

Solution 1

CEST is Central European Summer Time. It is the same as CET with daylight savings into effect.

Solution 2

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 see all available IDs.

EDIT: you can also use a new SimpleTimeZone

    TimeZone.setDefault(new SimpleTimeZone(60 * 60 * 1000, "CET"));
Share:
19,820
Romain Linsolas
Author by

Romain Linsolas

As a software engineer and specialist in Java / J2EE application development, I am particularly interested in designing and developing high performance JEE applications, and Rich Internet Applications. My specialties: IT Consulting in Java / J2EE development (Spring, Hibernate, JSF, Struts) Web development (XHTML, Javascript, CSS, Ajax) Agile methodologies (Scrum, eXtreme Programming) Unit Testing and Quality, Continuous Integration and Performance

Updated on June 09, 2022

Comments

  • Romain Linsolas
    Romain Linsolas almost 2 years

    Let's 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 running this code snippet, I have the following output:

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

    Why do I get different timezone ?

    Note that if I set the first date in august and the second one in september, the output will display the same timezone 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'm using Java 1.6.0_14