WoJ
WoJ

Reputation: 30035

How to parse UNIX timestamps with luxon?

I tried to use the luxon library to move away from moment - to translate the 1615065599.426264 timestamp into an ISO date.

According to the Online Epoch Converter this corresponds to

GMT: Saturday, March 6, 2021 9:19:59.426 PM
Your time zone: Saturday, March 6, 2021 10:19:59.426 PM GMT+01:00
Relative: 3 days ago

Removing the decimal part gives the same result.

The code using luxon:

let timestamp = 1615065599.426264
console.log(luxon.DateTime.fromMillis(Math.trunc(timestamp)).toISO())
console.log(luxon.DateTime.fromMillis(timestamp).toISO())
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

This result is

1970-01-19T17:37:45.599+01:00
1970-01-19T17:37:45.599+01:00

It is suspiciously close to Unix Epoch (1970-01-01 00:00:00).

Where is my mistake?

Upvotes: 18

Views: 30837

Answers (3)

Vadorequest
Vadorequest

Reputation: 18009

Just to give a more complete answer, there are indeed 2 ways of storing timestamps: Seconds and milliseconds precisions.

JavaScript indeed uses ms precision by default.

Luxon provides 2 different methods:

  • DateTime.fromMillis(1691760353000)
  • DateTime.fromSeconds(1691760353)

Both will produce the same output when calling date.toISO():

  • 2023-08-11T13:25:53.000+00:00

Depending on which precision you use, you need to use one or the other.

I wrote this answer because the other answer didn't make that crystal clear, and I found myself using toSeconds when what I really wanted was toMillis.

Upvotes: 9

SenatorWaffles
SenatorWaffles

Reputation: 380

Luxon can accept UNIX / epoch times in seconds with the .fromSeconds() function. You can then use the .toISO() function to output an ISO format.

in your specific example:

const { DateTime } = require('luxon')

//your other code here 

const myDateTime = DateTime.fromSeconds(1615065599.426264)
const myDateTimeISO = myDateTime.toISO()

//outputs '2021-03-07T08:19:59.426+11:00'

ref: https://moment.github.io/luxon/#/parsing?id=unix-timestamps

Upvotes: 23

m90
m90

Reputation: 11822

So called "Unix time" counts the number of seconds since 01.01.1970 whereas Luxon (and most things JavaScript) expects a value with a millisecond resolution.

Multiplying your value by 1000 will yield the expected result:

> let timestamp = 1615065599.426264
undefined
> new Date(timestamp).toJSON()
'1970-01-19T16:37:45.599Z'
> new Date(timestamp * 1000).toJSON()
'2021-03-06T21:19:59.426Z'

Upvotes: 9

Related Questions