Convert normal date to unix timestamp

2019-01-08 13:17发布

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.

10条回答
倾城 Initia
2楼-- · 2019-01-08 13:49
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.

查看更多
何必那么认真
3楼-- · 2019-01-08 13:55
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()).

查看更多
女痞
4楼-- · 2019-01-08 13:57

You can do it using Date.parse() Method.

Date.parse($("#yourCustomDate).val())

Date.parse("03.03.2016") output-> 1456959600000

Date.parse("2015-12-12") output-> 1449878400000

查看更多
一夜七次
5楼-- · 2019-01-08 13:58
new Date('2012.08.10').getTime() / 1000

Check the JavaScript Date documentation.

查看更多
孤傲高冷的网名
6楼-- · 2019-01-08 13:59

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();
查看更多
看我几分像从前
7楼-- · 2019-01-08 13:59

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

查看更多
登录 后发表回答