我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
当前回答
你只需要倒转你的日期数字,然后用,
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())));
}
这个重构的代码就可以做到这一点
let toTimestamp = strDate => Date.parse(strDate)
这适用于除ie8-以外的所有现代浏览器
更新:如果你来这里寻找当前的时间戳
Date.now(); //as suggested by Wilt
or
var date = new Date();
var timestamp = date.getTime();
或者简单地
new Date().getTime();
/* console.log(new Date().getTime()); */
下面的代码将把当前日期转换为时间戳。
var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);
您可以使用valueOf方法
new Date().valueOf()