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

new Date(myDate).getTime();

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


当前回答

对于那些希望具有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路径

其他回答

/**
 * Date to timestamp
 * @param  string template
 * @param  string date
 * @return string
 * @example         datetotime("d-m-Y", "26-02-2012") return 1330207200000
 */
function datetotime(template, date){
    date = date.split( template[1] );
    template = template.split( template[1] );
    date = date[ template.indexOf('m') ]
        + "/" + date[ template.indexOf('d') ]
        + "/" + date[ template.indexOf('Y') ];

    return (new Date(date).getTime());
}

+新的日期(替换) 这应该将myDate转换为timeStamp

第一个答案是好的,但是使用react typescript会报错,因为split(") 对我来说,更好的方法是。

parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))

很乐意帮忙。

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

更新:

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

对于那些希望具有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路径