convert date to timestamp in javascript?

2019-01-03 05:20发布

I want to convert date to timestamp, my input is 26-02-2012. I used

new Date(myDate).getTime();

It says NaN.. Can any one tell how to convert this?

10条回答
Melony?
2楼-- · 2019-01-03 05:43

To convert (ISO) date to Unix timestamp, I ended up with a timestamp 3 characters longer than needed so my year was somewhere around 50k...

I had to devide it by 1000: new Date('2012-02-26').getTime() / 1000

查看更多
三岁会撩人
3楼-- · 2019-01-03 05:44

There are two problems here. First, you can only call getTime on an instance of the date. You need to wrap new Date in brackets or assign it to variable.

Second, you need to pass it a string in a proper format.

Working example:

(new Date("2012-02-26")).getTime();
查看更多
Lonely孤独者°
4楼-- · 2019-01-03 05:49
function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}
查看更多
贼婆χ
5楼-- · 2019-01-03 05:51

this refactored code will do it

let toTimestamp = strDate => Date.parse(strDate)

this works on all modern browsers except ie8-

查看更多
登录 后发表回答