Java – convert local time to UTC time considering daylight saving time and vice versa

I know how to convert local time to UTC time and vice versa

Anyone can answer the following questions: 1 When converting between time zones, does java process DST internally? 2. What needs to be done when switching between time zones? Any good article on this clearer explanation?

Thank you in advance

Solution

Are you sure you know how to convert dates to UTC and return them? correct?

>Yes. > You don't need to convert, you just need to assign the correct timezone. > You need an article? OK, I'm doing it, but now let me give the answer here

The first is in advance Your program should store date (or calendar) inside UTC timezone Well, in fact, at GMT, because Java doesn't have leap seconds, but this is another story The only place you need to "convert" is when you want to show the user the time This is also sending email In both cases, you need to format the date to get its textual representation To do this, you will use dateformat and assign the 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 Of course, you can handle it manually. Just read the timezone related Javadoc

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>