我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
当前回答
/**
* 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路径
它应该是这个标准日期格式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)
在某些情况下,某些日期似乎是顽固的,也就是说,即使使用日期格式,如“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();
这对我来说很有效!干杯!
第一个答案是好的,但是使用react typescript会报错,因为split(") 对我来说,更好的方法是。
parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))
很乐意帮忙。
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())));
}