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.
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.
You could simply use the unary + operator
(+new Date('2012.08.10')/1000).toFixed(0);
http://xkr.us/articles/javascript/unary-add/ - look under Dates.
After comparing timestamp with the one from PHP, none of the above seems correct for my timezone. The code below gave me same result as PHP which is most important for the project I am doing.
function getTimeStamp(input) {
var parts = input.trim().split(' ');
var date = parts[0].split('-');
var time = (parts[1] ? parts[1] : '00:00:00').split(':');
// NOTE:: Month: 0 = January - 11 = December.
var d = new Date(date[0],date[1]-1,date[2],time[0],time[1],time[2]);
return d.getTime() / 1000;
}
// USAGE::
var start = getTimeStamp('2017-08-10');
var end = getTimeStamp('2017-08-10 23:59:59');
console.log(start + ' - ' + end);
I am using this on NodeJS, and we have timezone 'Australia/Sydney'. So, I had to add this on .env file:
TZ = 'Australia/Sydney'
Above is equivalent to:
process.env.TZ = 'Australia/Sydney'
unix timestamp
is so fundamental to all the engineering and computer science. Wish there was built-in convenience method. Currently I'm usingMath.floor((+new Date()) / 1000);
– Mars Robertson