How to convert UTC and local timezone in Java

后端 未结 3 983
谎友^
谎友^ 2020-12-09 00:11

I am curious about timezone in Java. I want to get UTC time in milliseconds from a device and send to server. Server will convert it to local timezone when it displays time

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 00:38

    UPDATE: This Answer is now out-of-date. The Joda-Time library is now supplanted by the java.time framework built into Java 8 and later. See this new Answer.

    Three-Letter Codes

    You should avoid using 3 or 4 letter time zone codes such as EST or IST. They are neither standard nor unique.

    Use proper time zone names, mostly Continent/CityOrRegion such as America/Montreal or Asia/Kolkata.

    Joda-Time

    The java.util.Date/Calendar classes are notoriously bad. Avoid using them. Use either Joda-Time or, in Java 8, the new java.time.* classes defined by JSR 310 and inspired by Joda-Time.

    Notice how much simpler and more obvious is the Joda-Time code shown below. Joda-Time even knows how to count – January is 1, not 0!

    Time Zone

    In Joda-Time, a DateTime instance knows its own time zone.

    Sydney Australia has a standard time of 10 hours ahead of UTC/GMT, and a Daylight Saving Time (DST) of 11 hours ahead. DST applies to the date specified by the question.

    Tip: Don't think like this…

    UTC time is 11 hours later than mine

    Think like this…

    Sydney DST is 11 hours ahead of UTC/GMT.

    Date-time work becomes easier and less error-prone if you think, work, and store in UTC/GMT. Only convert to localized date-time for presentation in the user-interface. Think globally, display locally. Your users and your servers can easily move to other time zones, so forget about your own time zone. Always specify a time zone, never assume or rely on default.

    Example Code

    Here is some example code using Joda-Time 2.3 and Java 8.

    // Better to specify a time zone explicitly than rely on default.
    // Use time zone names, not 3-letter codes. 
    // This list is not quite up-to-date (read page for details): http://joda-time.sourceforge.net/timezones.html
    DateTimeZone timeZone = DateTimeZone.forID("Australia/Sydney");
    DateTime dateTime = new DateTime(2014, 1, 14, 11, 12, 0, timeZone);
    DateTime dateTimeUtc = dateTime.toDateTime(DateTimeZone.UTC); // Built-in constant for UTC (no time zone offset).
    

    Dump to console…

    System.out.println("dateTime: " + dateTime);
    System.out.println("dateTimeUtc: " + dateTimeUtc);
    

    When run…

    dateTime: 2014-01-14T11:12:00.000+11:00
    dateTime in UTC: 2014-01-14T00:12:00.000Z
    

提交回复
热议问题