timestamp in JavaScript:
The Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.

Syntax

jQuery Code
var timeInMs = Date.now();
var timeStamp = Math.floor(Date.now() / 1000);
[ad type=”banner”]

Get a UNIX timestamp with Javascript

jQuery Code
var ts = Math.round((new Date()).getTime() / 1000);

Return value

A Number representing the milliseconds elapsed since the UNIX epoch.

Description

Because now() is a static method of Date, we always use it as Date.now().

Usage

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.

Example1:

Date.getUnixTime() returns the Unix epoch time.

We frequently need to calculate with unix timestamp. There are several ways to grab the timestamp. For current unix timestamp easiest and fastest way is

jQuery Code
const dateTime = Date.now();
const timestamp = Math.floor(dateTime / 1000);

or

jQuery Code
const dateTime = new Date().getTime();
const timestamp = Math.floor(dateTime / 1000);

To get unix timestamp of a specific date pass YYYY-MM-DD or YYYY-MM-DDT00:00:00Z as parameter of Date constructor.

jQuery Code
const dateTime = new Date('2012-06-08').getTime();
const timestamp = Math.floor(dateTime / 1000);

we can just add a + sign also when declaring a Date object like below

jQuery Code
const dateTime = +new Date();
const timestamp = Math.floor(dateTime / 1000);

[ad type=”banner”]

or for specific date

jQuery Code
const dateTime = +new Date('2012-06-08');
const timestamp = Math.floor(dateTime / 1000);

Example2:

Date.now() polyfill for older browsers.

This method was standardized in ECMA-262 5th edition.
Engines which have not been updated to support this method can work around the absence of this method using the following shim:

jQuery Code
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}

Solution

To copy & paste the following code at the beginning of your JavaScript:

jQuery Code
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(); }

[ad type=”banner”]

Categorized in: