Search code examples
scalajodatimeunix-timestamp

Same unixtime yields different date time in joda than the correct date time


I read from a very old post here on stackoverflow that joda is a possible solution to convert Unix timestamp.

import org.joda.time._
new DateTime(1511544070).toString("yyyy-MM-dd")

I got 1970-01-18 for this case, however, this is wrong because the date should be according to this online converter: 11/24/2017 @ 5:21pm (UTC)

It is possible the online converter is correct because the sample unix timestamp 1511544070 is from a dataset that date range is November 25 to December 03, 2017, the dataset is from China time which is 8 hours ahead of UTC, meaning 11/24/2017 @ 5:21pm (UTC) is actually 11/25/2017 @ 1:21am (Beijing Time)

Where can I get a working library or is there a working library that can get the same result like the online converter?


Solution

  • You can do that using java.time:

    import java.time.{ LocalDateTime, ZoneOffset }
    import java.time.format.DateTimeFormatter
    
    LocalDateTime.ofEpochSecond(1511544070, 0, ZoneOffset.UTC)
      .format(DateTimeFormatter.ofPattern("yyyy-MM-dd @ h:mm a"))