Last Updated: June 26, 2023
·
302K
· andreaspizsa

How to get the correct Unix Timestamp from any Date in JavaScript

A generic solution to get the Unix timestamp of any JavaScript Date object.

// Copy & Paste this
Date.prototype.getUnixTime = function() { return this.getTime()/1000|0 };
if(!Date.now) Date.now = function() { return new Date(); }
Date.time = function() { return Date.now().getUnixTime(); }

// Get the current time as Unix time
var currentUnixTime = Date.time();
currentUnixTime = Date.now().getUnixTime(); // same as above

// Parse a date and get it as Unix time
var parsedUnixTime = new Date('Mon, 25 Dec 1995 13:30:00 GMT').getUnixTime();
// parsedUnixTime==819898200

Motivation

Unix time (AKA epoch time) is used widely in Unix-like and many other operating systems and file formats. Unfortunately, there's a small discrepancy between the C-style time() call and JavaScript's Date.getTime():

A Unix timestamp is defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.

JavaScript's Date.getTime() returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).

Solution

Copy & paste the following code at the beginning of your JavaScript:

Date.prototype.getUnixTime = function() { return this.getTime()/1000|0 };
if(!Date.now) Date.now = function() { return new Date(); }
Date.time = function() { return Date.now().getUnixTime(); }

*** Done! ***

Usage

The three lines above add:

  • Date.getUnixTime() returns the Unix epoch time.
  • Date.now() polyfill for older browsers.
  • Date.time() is a a C-style helper function that returns the current Unix time.

Get the current time as a Unix timestamp

var currentUnixTime = Date.time();

which is short for

var currentUnixTime = Date.now().getUnixTime();

Get the current time as JavaScript Date Object

var currentTime = Date.now();

Get the Unix time of any JavaSript Date object

var someDate = new Date('Mon, 25 Dec 1995 13:30:00 GMT');
var theUnixTime = someDate.getUnixTime();

Related work


Please upvote.

2 Responses
Add your response

Putting aside the problematic practice of mutating shares global state, the motivation is wrong. Unix time is wrong. Interoperating with already broken code is the only valid reason to want such an awful thing.

over 1 year ago ·

No one should ever actually do this.

over 1 year ago ·