rbfl6g
Last Updated: September 29, 2018
·
145.8K
· 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.

3 Responses
Add your response

29628

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.

9 months ago ·
30470

Fundamental devices will normally hold up to 100 spheres in a leading tons basket. https://ru.pinterest.com/Pingpongguide/ping-pong-guide/ The Butterfly Amicus Professional does not obtain.

3 months ago ·
30842

We believe the smaller sized dimensions utilize http://dogharnessfunction.mihanblog.com/ narrower, thinner and a lot more http://dogharnessexecution.esportsify.com/articles/news/Unknown/3/best-dog-harness-for-small-dogs-four-awesome-choices-for-2018 supple webbing which should guarantee.

about 1 month ago ·