Convert Date by TimeZone

后端 未结 2 1837
半阙折子戏
半阙折子戏 2021-01-23 21:40

In that code above I want to transform a Date by the TimeZone of Server (GMT-02:00) to TimeZone from my Device (GMT-03:00). But I Always have the same Date of the server. What I

相关标签:
2条回答
  • 2021-01-23 22:01

    java.time

    Java 8 and later has the java.time framework built-in. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. These new java.time classes supplant the notoriously troublesome old date-time classes bundled with the earliest versions of Java, java.util.Date/.Calendar.

    Basics of java.time… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.

    Your example code uses only offset-from-UTC. A timezone is an offset plus a set of rules about adjusting for anomalies such as Daylight Saving Time (DST). So use a proper time zone name whenever possible. But if not possible, use ZoneOffset to get an OffsetDateTime.

    By the way, general best practice is to keep your servers in UTC. But that's another discussion.

    First get the current date-time from your server.

    Instant now = Instant.now();  // UTC.
    ZoneOffset offsetServer = ZoneOffset.of ( "-02:00" ); // Or ZoneOffset.systemDefault ()
    OffsetDateTime odtServer = OffsetDateTime.ofInstant( instant , offsetServer );
    

    Or we can shorten that to:

    ZoneOffset offsetServer = ZoneOffset.of ( "-02:00" ); // Or ZoneOffset.systemDefault ()
    OffsetDateTime odtServer = OffsetDateTime.now ( offsetServer );
    

    Define the desired offset. Apply that offset to the server’s current date-time to adjust.

    ZoneOffset offsetDesired = ZoneOffset.of ( "-03:00" );
    OffsetDateTime odtDesired = odtServer.withOffsetSameInstant ( offsetDesired );
    

    Dump to console.

    System.out.println ( "instant: " + instant + " | odtServer: " + odtServer + " | odtDesired: " + odtDesired );
    

    instant: 2016-01-22T22:16:14.386Z | odtServer: 2016-01-22T20:16:14.386-02:00 | odtDesired: 2016-01-22T19:16:14.386-03:00

    Those textual representations of the date-time values are formatted by default in the toString method using the ISO 8601 standard. You can define other formats as needed; search StackOverflow for many examples.

    0 讨论(0)
  • 2021-01-23 22:08

    What I doing wrong?

    You're assuming that a Date has a time zone to start with. It doesn't. A Calendar does, but a Date is just milliseconds since the Unix epoch. It doesn't know about calendar systems or time zones. It's just a point in time.

    It's not clear what you want to do with the result - but if it's a matter of formatting it for display, just use SimpleDateFormat and set the time zone on that instead.

    I would also strongly recommend that you use Joda Time instead of the built-in types... it's a much more sensible API.

    0 讨论(0)
提交回复
热议问题