Does Java automatically switch daylight saving time?

Short answer: Yes, it does.

Long answer: The time in Java is just a simple long value (milliseconds since 1970) without any information about the time zone. The java.util.Date and java.sql.Date also store the date/time internally as milliseconds since 1970, but with an UTC time zone attached.

The time zone comes into play, when you format a date/time for output or when you parse a date/time from a string. The default time zone can be set through the -Duser.timezone system property during startup, or alternatively by calling the TimeZone.setDefault() method.

You can test it using a small test program. In most European countries, the switch to DST will happen on March 31st 2013 at 2am.
So here is a small program that loops 5 times from March 30th 11pm in one hour steps:

public static void main(String[] args) {
    Calendar c = Calendar.getInstance();
    c.set(2013, 2, 30, 23, 0, 0);
    long start = c.getTimeInMillis();
    long oneHour = 1000 * 60 * 60;
    long t = start;
    for (int i = 0; i < 5; i++) {
        System.out.println(new Date(t));
        t = t + oneHour;
    }
}

Starting it with -Duser.country=DE -Duser.timezone=GMT it will print the following:

Sat Mar 30 23:00:00 GMT 2013
Sun Mar 31 00:00:00 GMT 2013
Sun Mar 31 01:00:00 GMT 2013
Sun Mar 31 02:00:00 GMT 2013
Sun Mar 31 03:00:00 GMT 2013

Note that there is no switch.

Starting it with -Duser.country=DE -Duser.timezone=CET it will print the following:

Sat Mar 30 23:00:00 CET 2013
Sun Mar 31 00:00:00 CET 2013
Sun Mar 31 01:00:00 CET 2013
Sun Mar 31 03:00:00 CEST 2013
Sun Mar 31 04:00:00 CEST 2013

Note the Central European Time switch between 1am and 3am.

Starting it with -Duser.country=DE -Duser.timezone=EET it will print the following:

Sat Mar 30 23:00:00 EET 2013
Sun Mar 31 00:00:00 EET 2013
Sun Mar 31 01:00:00 EET 2013
Sun Mar 31 02:00:00 EET 2013
Sun Mar 31 04:00:00 EEST 2013

Note the Eastern European Time switch between 2am and 4am, because EET is CET plus one hour.

Advertisements