2

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 ?

Avin Pereira
  • 57
  • 2
  • 5
  • Instant or Date used for store data, they don't store any format, you can convert them in your desire format string – Eklavya Jun 12 '20 at 19:25
  • Does this answer your question? [Format Instant to String](https://stackoverflow.com/questions/25229124/format-instant-to-string) – Eklavya Jun 12 '20 at 19:29
  • 2
    Accorindg to [Epoch & Unix Timestamp Conversion Tools](https://www.epochconverter.com/) 2020-06-12T18:54:31Z is perfectly accurate. The trailing `Z` means UTC (what is called GMT on the linked page). – Ole V.V. Jun 12 '20 at 19:52
  • 2
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. They deceive you into wrong beliefs about the correct answer. Instead use `Instant`, `ZoneId`, and `ZonedDateTime`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 12 '20 at 19:55

1 Answers1

2

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]
rahul
  • 1,281
  • 2
  • 12
  • 29