我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
当前回答
您的字符串不是Date对象指定要处理的格式。您必须自己解析它,使用像MomentJS这样的日期解析库或更老的DateJS(据我所知,目前还没有维护),或者在要求date解析它之前将其调整为正确的格式(例如,2012-02-29)。
为什么你得到NaN:当你要求new Date(…)处理一个无效的字符串时,它返回一个Date对象,该对象被设置为无效的日期(new Date("29-02-2012"). tostring()返回" invalid Date ")。在此状态下对日期对象调用getTime()将返回NaN。
其他回答
+新的日期(替换) 这应该将myDate转换为timeStamp
简单地在Date对象上执行一些算术运算将返回时间戳作为数字。这对于简洁表示法很有用。我发现这是最容易记住的方法,因为该方法也适用于将转换为字符串类型的数字转换回数字类型。
let d = new Date(); Console.log (d, d * 1);
为了将(ISO)日期转换为Unix时间戳,我最终得到了一个比所需时间长3个字符的时间戳,所以我的年份大约是50k…
我要除以1000 new Date('2012-02-26').getTime() / 1000
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())));
}
更新:如果你来这里寻找当前的时间戳
Date.now(); //as suggested by Wilt
or
var date = new Date();
var timestamp = date.getTime();
或者简单地
new Date().getTime();
/* console.log(new Date().getTime()); */