I have a Spring Boot server that returns me a date as follows:
{
// Some keys
pickupDate: {
epochSecond: 1612199331,
nano: 428000000
},
// Some other keys
}
How can I convert that object to a JavaScript Date?
new Date( ( 1_612_199_331 * 1_000 ) + ( 428_000_000 / 1_000_000 ) )
If those values come from objects in the java.time classes of Java 8 and later such as Instant
, then:
epochSecond
represents a count of whole seconds since the epoch reference of the first moment of 1970 as seen in UTC, 1970-01-01T00:00Z. nano
represents a fractional second as a count of nanoseconds , billionths of a second. While I do not know JavaScript, it seems that most implementations offer a Date
type. A Date
represents a moment as seen in UTC based on a count from the same epoch reference as java.time .
The difference is the granularity of the fractional second. The JavaScript Date
uses milliseconds rather the nanoseconds in java.time . So you will need to divide that count of nanos by 1,000,000 to get millis.
Multiply the whole seconds by a thousand to get milliseconds. And divide the count of nanos by a million to get milliseconds. Sum to get a total number of milliseconds since epoch reference. Pass to constructor of Date
.
const d =
new Date(
( 1_612_199_331 * 1_000 )
+
( 428_000_000 / 1_000_000 )
)
;
Generate text representing the moment stored in that Date
using standard ISO 8601 format.
const d = new Date( ( 1_612_199_331 * 1_000 ) + ( 428_000_000 / 1_000_000 ) ) ;
console.log( d.toISOString() ) ;
2021-02-01T17:08:51.428Z
The Z
on the end means an offset of zero hours-minutes-seconds from UTC. Pronounced “Zulu”.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.