我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
当前回答
下面的代码将把当前日期转换为时间戳。
var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);
其他回答
第一个答案是好的,但是使用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());
}
只是提醒一下
Date.parse(“2022 - 08 - 04 - t04:02:10.909z”)
1659585730909
日期。解析(新日期(“2022 - 08 - 04 - t04:02:10.909z”))
1659585730000
其他开发人员已经提供了答案,但在我自己的方式中,你可以在不创建任何用户定义函数的情况下执行此操作,如下所示:
var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000
简单地在Date对象上执行一些算术运算将返回时间戳作为数字。这对于简洁表示法很有用。我发现这是最容易记住的方法,因为该方法也适用于将转换为字符串类型的数字转换回数字类型。
let d = new Date(); Console.log (d, d * 1);