Java versus Daylight savings time

Depending on the version of the Java runtime and the location of the host, the Java Date and Calendar routines may take daylight savings time into account. For example:

  • If you set a Calendar or Date to a specific value and then read it back, you may end up with a time later than the one you set. (You could even conceivably end up with an earlier time if you set it a millisecond before daylight savings time ends, and then read it back after.)
  • If you add a duration to a date, you may end up with a date earlier or later than you expect. You may even end up with exactly the same date, or one even earlier than what you started with. Similar surprises may occur when you subtract duration from a date.

This can be dangerous in time-based loops that expect each time to be strictly greater than the previous time. Without care, infinite loops can result.

Also remember that results are usually dependent on the default time zone. So even if the program works for you, it may fail mysteriously at the deployment site in Novosibirsk.

Share This | Comments | Permalink | Trackback | Comments feed

4 responses

  • ye man, we know this is a problem, do you have any recomendations to fix these problem

    Kumaresan | 3 October 2006
  • I am facing problem while setting daylight savings in my pc. While running my application it shows system time. but not reflected US,Canada Estern time(5.00).
    I used Java Calander and Date for display timing in my application with JDK 1.5

    For US,CANADA it shows 1 Hr behind and for other region it shows correct time.
    please clarify

    GMAN | 27 March 2008
  • Use something like this:
    createTime = creationCal.getTimeInMillis() + creationCal.getTimeZone().getOffset(creationCal.getTimeInMillis());

    todayTime = todayCal.getTimeInMillis() + todayCal.getTimeZone().getOffset(todayCal.getTimeInMillis());

    diff = todayTime - createTime;
    days = diff / MILLISECONDS_PER_DAY;

    The offset piece takes care of this problem

    Asim Masood | 28 March 2008
  • creationCal and todayCal are GregorianCalendar objects

    Asim Masood | 28 March 2008

Post a comment

(required)
(required)
Close
E-mail It