Given a string like 2022-01-01 13:00:00
, which represents a time in the Europe/Paris
timezone, how can we get the corresponding Unix Timestamp in JavaScript? This problem is sufficiently complex that in my opinion leveraging a third-party library is the best solution.
Luxon
I’m using Luxon, a library for dealing with dates and times in JavaScript. I add this library to my project by running the following from the command line
npm install luxon
Now, in the React component where I want to get the Unix timestamp I add
import { DateTime } from 'luxon';
const myDateTimeStr = '2022-01-01 13:00:00';
const unixTimestamp = DateTime.fromFormat(
myDateTimeStr,
'yyyy-MM-dd HH:mm:ss',
{
zone: 'Europe/Paris',
},
).toSeconds();
Other Options
If we want the timestamp in milliseconds (instead of seconds), we can use .toMillis()
instead of .toSeconds()
.
The format yyyy-MM-dd HH:mm:ss
comes from this Table of tokens. If our string comes to us as a variation of the ISO 8601 format, we can use .fromISO()
instead of the more versatile .fromFormat()
.
Leave a Reply