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

new Date(myDate).getTime();

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


当前回答

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

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

其他回答

这里有两个问题。 首先,您只能在日期的实例上调用getTime。您需要将new Date括在括号中或将其赋值给变量。

其次,您需要以适当的格式传递一个字符串。

工作的例子:

(new Date("2012-02-26")).getTime();

它应该是这个标准日期格式YYYY-MM-DD,以使用下面的等式。例如:2020-04-24 16:51:56或2020-04-24T16:51:56+05:30。它将工作良好,但日期格式应该像这样的YYYY-MM-DD。

var myDate = "2020-04-24";
var timestamp = +new Date(myDate)
/**
 * 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());
}

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

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

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