Search code examples
javaspring-bootdatetimepojoepoch

How to convert an Epoch timestamp into an object of type java.time.Instant Accurately in Java?


I have a Spring Boot JPA Application that interacts with a 3rd party API. The response payload of the API has a key

"created_at": 1591988071

I need to parse this field into java.time.Instant so that I can do some comparisons with the value I have in the Database. I have learned that I can use the below mentioned piece of code.

    Instant instant = Instant.ofEpochSecond(1591988071);

Output :

    2020-06-12T18:54:31Z

But to be honest, this output is off by a couple of hours.

I found another approach, wherein if I use

    String dateAsText = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            .format(new Date(1591988071 * 1000L));
    System.out.println(dateAsText);

I get the desired output but in String format.

    2020-06-13 00:24:31

Can someone tell me how to obtain the above String output but converted into type java.time.Instant ?


Solution

  • It is likely you're in a different timezone than UTC. The instant is giving you time in UTC. That's indicated by the Z at the end of your first output.

    You would want to look at atZone

    Instant instant = Instant.ofEpochSecond(1591988071);
    System.out.println(instant);
    final ZonedDateTime losAngeles = instant.atZone(ZoneId.of("America/Los_Angeles"));
    System.out.println(losAngeles);
    final ZonedDateTime mumbai = instant.atZone(ZoneId.of("UTC+0530"));
    System.out.println(mumbai);
    

    This gives you something you might expect

    2020-06-12T18:54:31Z
    2020-06-12T11:54:31-07:00[America/Los_Angeles]
    2020-06-13T00:24:31+05:30[UTC+05:30]