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

new Date(myDate).getTime();

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


当前回答

+新的日期(替换) 这应该将myDate转换为timeStamp

其他回答

更新:如果你来这里寻找当前的时间戳

Date.now(); //as suggested by Wilt

or

var date      = new Date();
var timestamp = date.getTime();

或者简单地

new Date().getTime();
/* console.log(new Date().getTime()); */

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

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

工作的例子:

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

如果你还需要增加时间,这个方法也能奏效 new Date('2021-07-22 07:47:05.842442+00').getTime()

这在没有时间的情况下也同样有效 new Date('2021-07-22 07:47:05.842442+00').getTime()

这也可以工作,但它不会接受时间 新日期(2021/07/22).getTime ()

最后,如果所有的都不工作,使用这个 日期(年,月,日,时,分,秒,毫秒)

注意,对于Month,计数从0开始,因此Jan === 0, Dec === 11

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

一幅图胜过千言万语:)

在这里,我将当前日期转换为时间戳,然后将时间戳转换为当前日期,我们将展示如何将日期转换为时间戳,并将时间戳转换为日期。