我想将日期转换为时间戳,我的输入是26-02-2012。我使用

new Date(myDate).getTime();

上面写着NaN..有人能告诉我怎么转换吗?


当前回答

只是提醒一下

Date.parse(“2022 - 08 - 04 - t04:02:10.909z”)

1659585730909

日期。解析(新日期(“2022 - 08 - 04 - t04:02:10.909z”))

1659585730000

其他回答

只是提醒一下

Date.parse(“2022 - 08 - 04 - t04:02:10.909z”)

1659585730909

日期。解析(新日期(“2022 - 08 - 04 - t04:02:10.909z”))

1659585730000

你只需要倒转你的日期数字,然后用,

new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11)

在你的情况下:

var myDate="26-02-2012";
myDate=myDate.split("-");
new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime();

附注:英国地区在这里并不重要。

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())));
}

更新:如果你来这里寻找当前的时间戳

Date.now(); //as suggested by Wilt

or

var date      = new Date();
var timestamp = date.getTime();

或者简单地

new Date().getTime();
/* console.log(new Date().getTime()); */

这个重构的代码就可以做到这一点

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

这适用于除ie8-以外的所有现代浏览器