Converting local time to UTC time or vice versa considering daylight saving time

Newbie picture Newbie · May 14, 2011 · Viewed 32.7k times · Source

I know how to convert local time to UTC time and vice versa. But I am very much confused about daylight savings time(DST) handling while doing this.

So can anyone answer the below questions:
1. Does java internally handle DST when converting between timezones?
2. What things I need to do while converting between timezones?
3. Any good article which explains about this more clearly?

Thanks in advance.

Answer

Paweł Dyda picture Paweł Dyda · May 14, 2011

Are you sure you know how to convert dates to UTC and back? Correctly?
I am afraid, I doubt that.

  1. Yes.
  2. You don't need to convert, you just need to assign correct TimeZone.
  3. What you need an article for? OK, I am working on this, but for now let me put an answer here.

The first thing first. Your program should store Date (or Calendar) in UTC TimeZone internally. Well, in fact in GMT, because there are no leap seconds in Java, but that is another story.
The only place when you should be in need of "converting", is when you are going to display the time to user. That regards to sending email messages as well. In both cases you need to format date to get its textual representation. To that you would use DateFormat and assign correct TimeZone:

    // that's for desktop application
    // for web application one needs to detect Locale
    Locale locale = Locale.getDefault();
    // again, this one works for desktop application
    // for web application it is more complicated
    TimeZone currentTimeZone = TimeZone.getDefault();
    // in fact I could skip this line and get just DateTime instance,
    // but I wanted to show how to do that correctly for
    // any time zone and locale
    DateFormat formatter = DateFormat.getDateTimeInstance(
            DateFormat.DEFAULT,
            DateFormat.DEFAULT,
            locale);
    formatter.setTimeZone(currentTimeZone);

    // Dates "conversion"
    Date currentDate = new Date();
    long sixMonths = 180L * 24 * 3600 * 1000;
    Date inSixMonths = new Date(currentDate.getTime() + sixMonths);

    System.out.println(formatter.format(currentDate));
    System.out.println(formatter.format(inSixMonths));
    // for me it prints
    // 2011-05-14 16:11:29
    // 2011-11-10 15:11:29

    // now for "UTC"
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println(formatter.format(currentDate));
    System.out.println(formatter.format(inSixMonths));
    // 2011-05-14 14:13:50
    // 2011-11-10 14:13:50

As you can see, Java cares about handling DST. You can of course handle it manually, just read the TimeZone related JavaDoc.