In joda time how to convert time zone without changing time

后端 未结 7 1975
一生所求
一生所求 2020-12-04 19:06

I am getting UTC timestamp from database which is I am setting into a JodaTime DateTime instance

DateTime dt = new DateTime(timestamp.getTime())         


        
相关标签:
7条回答
  • 2020-12-04 19:51

    None of the given answers actually explained the problem. The real problem is the initial assumptions were incorrect. The timestamp from the database was created using the local JVM timezone Asia/Kolkata and not UTC. This is the default behavior with JDBC which is why it's still recommended to set your JVM timezone to UTC.

    If the timestamp from the database were in fact:

    2013-09-25 11:27:34 AM UTC
    

    Or in ISO-8601 format:

    2013-09-25T11:27:34Z // The trailing 'Z' means UTC
    

    Then using the new DateTime(timestamp, DateTimeZone.UTC) constructor works fine. See for yourself:

    Timestamp timestamp = new Timestamp(1380108454000L);
    DateTime dt = new DateTime(timestamp.getTime(), DateTimeZone.UTC);
    System.out.println(dt); // => 2013-09-25T11:27:34.000Z
    

    If you're wondering how I got 1380108454000L, I simply used the Joda parsing classes:

    ISODateTimeFormat.dateTimeParser().parseMillis("2013-09-25T11:27:34Z")
    

    Alternatively there are websites online where you can enter a date, time, and timezone and it returns the epoch value in milliseconds or vice versa. It's sometimes good as a sanity check.

    // https://www.epochconverter.com
    Input: 1380108454000  Click: "Timestamp to Human Date"
    Assuming that this timestamp is in milliseconds:
    GMT: Wednesday, September 25, 2013 11:27:34 AM
    

    Also, keep in mind the java.sql.Timestamp class roughly correlates to the Joda/Java 8+ Instant class. Sometimes it's easier to convert between equivalent classes to spot bugs like this earlier.

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