How to generate timestamp unix epoch format nodejs?

The native JavaScript Date system works in milliseconds as opposed to seconds, but otherwise, it is the same "epoch time" as in UNIX.

You can round down the fractions of a second and get the UNIX epoch by doing:

Math.floor(+new Date() / 1000)

Update: As Guillermo points out, an alternate syntax may be more readable:

Math.floor(new Date().getTime() / 1000)

The + in the first example is a JavaScript quirk that forces evaluation as a number, which has the same effect of converting to milliseconds. The second version does this explicitly.


If you can, I highly recommend using moment.js. To get the number of milliseconds since UNIX epoch, do

moment().valueOf()

To get the number of seconds since UNIX epoch, do

moment().unix()

You can also convert times like so:

moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()

I do that all the time.

To install moment.js on Node,

npm install moment

and to use it

var moment = require('moment');
moment().valueOf();

ref


Helper methods that simplifies it, copy/paste the following on top of your JS:

Date.prototype.toUnixTime = function() { return this.getTime()/1000|0 };
Date.time = function() { return new Date().toUnixTime(); }

Now you can use it wherever you want by simple calls:

// Get the current unix time: 
console.log(Date.time())

// Parse a date and get it as Unix time
console.log(new Date('Mon, 25 Dec 2010 13:30:00 GMT').toUnixTime())

Demo:

     
    Date.prototype.toUnixTime = function() { return this.getTime()/1000|0 };
    Date.time = function() { return new Date().toUnixTime(); }

    // Get the current unix time: 
    console.log("Current Time: " + Date.time())

    // Parse a date and get it as Unix time
    console.log("Custom Time (Mon, 25 Dec 2010 13:30:00 GMT): " + new Date('Mon, 25 Dec 2010 13:30:00 GMT').toUnixTime())