Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java/JavaScript - java.time.Instant serialization to javascript Date [duplicate]

I have a web API endpoint that accepts a java.time.Instant instance, like so:

{ "time": "2015-07-23T10:31:33Z" }

When I get a response back, I get this:

{ "time": 1437647493 }

When I try to create a new Date instance in JavaScript like this:

new Date(1437647493);

I get this result:

Sat Jan 17 1970 15:20:47 GMT+0000 (GMT Standard Time)

What is the relationship between "2015-07-23T10:31:33Z" and 1437647493 and how do I parse the result to JavaScript's Date?

like image 437
Matthew Layton Avatar asked Aug 01 '26 09:08

Matthew Layton


1 Answers

1437647493 is the number of seconds since January 1, 1970. This is commonly known as a UNIX timestamp, and that date is the UNIX epoch.

Date expects the number of milliseconds since the UNIX epoch. Multiply by 1000 and you'll get the time you want.

new Date(1437647493L * 1000)

Or, in Java if you're using Instant, write:

Instant.ofEpochSecond(1437647493L)
like image 104
John Kugelman Avatar answered Aug 04 '26 00:08

John Kugelman