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

new Date(myDate).getTime();

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


当前回答

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

更新:

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

其他回答

试试这个函数,它使用Date.parse()方法,不需要任何自定义逻辑:

function toTimestamp(strDate){
   var datum = Date.parse(strDate);
   return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));

对于那些希望具有yyyymmddHHMMSS格式的可读时间戳的人

> (new Date()).toISOString().replace(/[^\d]/g,'')              // "20190220044724404"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -3) // "20190220044724"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -9) // "20190220"

使用示例:备份文件扩展名。/我的/ / my.file.js.20190220路径

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

在某些情况下,某些日期似乎是顽固的,也就是说,即使使用日期格式,如“2022-06-29 15:16:21”,您仍然会得到null或NaN。我必须通过在空白区域中加入一个“T”来解决我的问题,即:

const inputDate = "2022-06-29 15:16:21";
const newInputDate = inputDate.replace(" ", "T");

const timeStamp = new Date(newInputDate).getTime();

这对我来说很有效!干杯!

其他开发人员已经提供了答案,但在我自己的方式中,你可以在不创建任何用户定义函数的情况下执行此操作,如下所示:

var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000