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

new Date(myDate).getTime();

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


当前回答

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

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

很乐意帮忙。

其他回答

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

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

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

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

它应该是这个标准日期格式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.parse()方法,不需要任何自定义逻辑:

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

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