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

new Date(myDate).getTime();

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


当前回答

最简单和准确的方法是在日期之前添加一元操作符

console.log('时间戳是:${数字(+新日期())}')

其他回答

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

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

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

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()); */

将字符串拆分为多个部分,并将它们直接提供给Date构造函数:

更新:

这是计划 捐献 var新约会=新日期(单身约会,2—1—1,单身约会[0]); console.log (newDate.getTime ());

一幅图胜过千言万语:)

在这里,我将当前日期转换为时间戳,然后将时间戳转换为当前日期,我们将展示如何将日期转换为时间戳,并将时间戳转换为日期。