我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
我想将日期转换为时间戳,我的输入是26-02-2012。我使用
new Date(myDate).getTime();
上面写着NaN..有人能告诉我怎么转换吗?
当前回答
简单地在Date对象上执行一些算术运算将返回时间戳作为数字。这对于简洁表示法很有用。我发现这是最容易记住的方法,因为该方法也适用于将转换为字符串类型的数字转换回数字类型。
let d = new Date(); Console.log (d, d * 1);
其他回答
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())));
}
这里有两个问题。 首先,您只能在日期的实例上调用getTime。您需要将new Date括在括号中或将其赋值给变量。
其次,您需要以适当的格式传递一个字符串。
工作的例子:
(new Date("2012-02-26")).getTime();
它应该是这个标准日期格式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)
为了将(ISO)日期转换为Unix时间戳,我最终得到了一个比所需时间长3个字符的时间戳,所以我的年份大约是50k…
我要除以1000 new Date('2012-02-26').getTime() / 1000
一幅图胜过千言万语:)
在这里,我将当前日期转换为时间戳,然后将时间戳转换为当前日期,我们将展示如何将日期转换为时间戳,并将时间戳转换为日期。