How can I convert normal date 2012.08.10 to unix timestamp in javascript?

Fiddle: http://jsfiddle.net/J2pWj/




I've seen many posts here that convert it in PHP, Ruby, etc... But I need to do this inside JS.


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

Check the JavaScript Date documentation.


parseInt((new Date('2012.08.10').getTime() / 1000).toFixed(0))

It's important to add the toFixed(0) to remove any decimals when dividing by 1000 to convert from milliseconds to seconds.

The .getTime() function returns the timestamp in milliseconds, but true unix timestamps are always in seconds.


var d = '2016-01-01T00:00:00.000Z';
console.log(new Date(d).valueOf()); // returns the number of milliseconds since the epoch

You should check out the moment.js api, it is very easy to use and has lots of built in features.

I think for your problem, you could use something like this:

var unixTimestamp = moment('2012.08.10', 'YYYY.MM.DD').unix();

var date = new Date('2012.08.10');
var unixTimeStamp = Math.floor(date.getTime() / 1000);

In this case it's important to return only a whole number (so a simple division won't do), and also to only return actually elapsed seconds (that's why this code uses Math.floor() and not Math.round()).