我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
当前回答
你只需要倒转你的日期数字,然后用,
new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11)
在你的情况下:
var myDate="26-02-2012";
myDate=myDate.split("-");
new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime();
附注:英国地区在这里并不重要。
其他回答
第一个答案是好的,但是使用react typescript会报错,因为split(") 对我来说,更好的方法是。
parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))
很乐意帮忙。
试试这个函数,它使用Date.parse()方法,不需要任何自定义逻辑:
function toTimestamp(strDate){
var datum = Date.parse(strDate);
return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));
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())));
}
在某些情况下,某些日期似乎是顽固的,也就是说,即使使用日期格式,如“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();
这对我来说很有效!干杯!
简单地在Date对象上执行一些算术运算将返回时间戳作为数字。这对于简洁表示法很有用。我发现这是最容易记住的方法,因为该方法也适用于将转换为字符串类型的数字转换回数字类型。
let d = new Date(); Console.log (d, d * 1);