我想将日期转换为时间戳,我的输入是26-02-2012。我使用

new Date(myDate).getTime();

上面写着NaN..有人能告诉我怎么转换吗?


当前回答

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())));
}

其他回答

下面的代码将把当前日期转换为时间戳。

var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);

第一个答案是好的,但是使用react typescript会报错,因为split(") 对我来说,更好的方法是。

parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))

很乐意帮忙。

它应该是这个标准日期格式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)

简单地在Date对象上执行一些算术运算将返回时间戳作为数字。这对于简洁表示法很有用。我发现这是最容易记住的方法,因为该方法也适用于将转换为字符串类型的数字转换回数字类型。

let d = new Date(); Console.log (d, d * 1);

这里有两个问题。 首先,您只能在日期的实例上调用getTime。您需要将new Date括在括号中或将其赋值给变量。

其次,您需要以适当的格式传递一个字符串。

工作的例子:

(new Date("2012-02-26")).getTime();