Getting timestamps in Javascript

January 28, 2019

Timestamps are great to use when trying to avoid the differences in timezones and such. Now in Javascript, support for certain date related methods are broken in older browsers, so it's important to make sure that you can always retrieve a timestamp.

Quickest way to get a timestamp of the current time:

+new Date()

Another quick way (supported on many recent browsers):

Date.now()

// Browser Compatibility:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

You can also write a quick polyfill for Date.now() in case a browser doesn't support it:

if (!Date.now) {
    Date.now = () => new Date().getTime()
}

Keep in mind, timestamps are in milliseconds. To convert them into seconds, you should simply divide by 1000.

To get a timestamp of a specific date/time:

new Date("Jan 27 2019 15:30").getTime()