• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Programming / JavaScript Unix Timestamp from String in Time Zone

JavaScript Unix Timestamp from String in Time Zone

Last updated on February 27, 2022 by Sal Ferrarello

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().

Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit

Filed Under: Dev Tips, Programming, Solution Tagged With: DateTime, JavaScript, time zone

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in