How to convert UTC and local timezone in Java

后端 未结 3 984
谎友^
谎友^ 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

    tl;dr

    Use modern java.time classes.

    ZonedDateTime
    .of( 2014 , 1 , 14 , 11 , 12 , 0 , 0 , ZoneId.of( "Australia/Sydney" ) )
    .toInstant()
    .toEpochMilli() 
    

    1389658320000

    Going the other direction.

    Instant
    .ofEpochMilli( 1_389_658_320_000L )  // .toString(): 2014-01-14T00:12:00Z
    .atZone( 
        ZoneId.of( "Australia/Sydney" ) 
    )                                    // .toString(): 2014-01-14T11:12+11:00[Australia/Sydney]
    .format(
        DateTimeFormatter
        .ofPattern ( 
            "dd/MM/uuuu HH:mm:ss z" , 
            new Locale( "en" , "AU" ) 
        )
    )
    

    14/01/2014 11:12:00 AEDT

    java.time

    You are using terrible date-time classes that were made obsolete years ago by the adoption of JSR 310 defining the modern java.time classes.

    I am curious about timezone in Java.

    FYI, an offset-from-UTC is merely a number of hours-minutes-seconds. When we say “UTC” or put a Z at the end of a string, we mean an offset of zero hours-minutes-seconds, for UTC itself.

    A time zone is much more. A time zone is a history of past, present, and future changes to the offset used by the people of a particular region. Politicians around the world have an odd penchant for changing the offset of their jurisdiction.

    I want to get UTC time in milliseconds from a device and send to server.

    For the current moment, use Instant. An Instant internally is the number of whole seconds seconds since the epoch reference of first moment of 1970 UTC, plus a fraction of a second in nanoseconds.

    Instant now = Instant.now() ;  // Capture current moment in UTC.
    long millisecondsSinceEpoch = now.toEpochMilli() ;
    

    Going the other direction.

    Instant instant = Instant.ofEpochMilli( millisecondsSinceEpoch ) ;
    

    Server will convert it to local timezone …

    Specify the time zone desired/expected by the user.

    If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.

    Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

    ZoneId z = ZoneId.of( "America/Montreal" ) ;  
    ZonedDateTime zdt = instant.atZone( z ) ;
    

    … when it displays time to users

    Automatically localize for the user's language and culture.

    To localize, specify:

    • FormatStyle to determine how long or abbreviated should the string be.
    • Locale to determine:
      • The human language for translation of name of day, name of month, and such.
      • The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

    Example:

    Locale l = Locale.CANADA_FRENCH ;   // Or Locale.US, Locale.JAPAN, etc.
    DateTimeFormatter f = 
        DateTimeFormatter
        .ofLocalizedDateTime( FormatStyle.FULL )
        .withLocale( l )
    ;
    String output = zdt.format( f );
    

    Timezone in my system is Australia/Sydney( UTC + 11:00)

    The current default time zone of your server should be irrelevant to your program. Always specify the desired/expected time zone. Frankly, making optional the time zone (and Locale) argument of the various date-time methods is one of the very few design flaws in java.time framework.

    Tip: Generally best to set your servers to UTC as their current default time zone.

    By the way, be clear that time zone and locale have nothing to do with one another. You might want Japanese language for displaying a moment as seen in Africa/Tunis time zone.

    ZoneID zAuSydney = ZoneId.of( "Australia/Sydney" ) ;
    ZonedDateTime zdt = instant.atZone( zAuSydney ) ;
    String output = zdt.format(
        DateTimeFormatter
        .localizedDateTime( FormatStyle.LONG )
        .withLocale( new Locale( "en" , "AU" ) ;
    ) ;
    

    int year = 2014; …

    Note that java.time uses sane numbering, unlike the legacy classes. Months are 1-12 for January-December, and weekdays are 1-7 for Monday-Sunday.

    LocalDate ld = LocalDate.of( 2014 , 1 , 14 ) ;
    LocalTime lt = LocalTime.of( 11 , 12 ) ;
    ZoneId z = ZoneId.of( "Australia/Sydney" ) ;
    ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
    

    zdt.toString() = 2014-01-14T11:12+11:00[Australia/Sydney]

    Generally best to automatically localize for display, as seen above. But if you insist, you can hard-code a formatting pattern.

    Locale locale = new Locale ( "en" , "AU" );
    ZoneId z = ZoneId.of ( "Australia/Sydney" );
    ZonedDateTime zdt = ZonedDateTime.of ( 2014 , 1 , 14 , 11 , 12 , 0 , 0 , z );
    

    zdt.toString(): 2014-01-14T11:12+11:00[Australia/Sydney]

    Specify that formatting pattern of yours.

    DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd/MM/uuuu HH:mm:ss z" , locale );
    String output = zdt.format ( f );
    

    output = 14/01/2014 11:12:00 AEDT

    Your Question was interested in a count of milliseconds since epoch of 1970-01-01T00:00:00Z. So adjust from the Australia time zone to UTC. Same moment, same point on the timeline, different wall-clock time.

    Instant instant = zdt.toInstant() ;  // Adjust from time zone to UTC.
    

    instant.toString(): 2014-01-14T00:12:00Z

    Note the difference in hour-of-day between instant and zdt.

    I thought I could have 13/01/2014 00:12:00 for c2 because UTC time is 11 hours later than mine.

    ➥ As you asked for, twelve minutes after 11 AM in Sydney zone is the same moment as twelve minutes after midnight in UTC, because Australia/Sydney on that date is eleven hours ahead of UTC.

    Calculate milliseconds since epoch.

    long millisecondsSinceEpoch = instant.toEpochMilli() ;
    

提交回复
热议问题