比较javascript日期对象

时间:2013-10-16 15:43:24

标签: javascript date

我必须为何时更新刷新令牌做一个逻辑,不知怎的,我没有得到正确的值。

 console.log(this._accessToken[".expires"]);
 console.log(Date.parse(this._accessToken[".expires"]) > new Date().getTime());

结果

Wed, 16 Oct 2013 15:42:53 GMT 
true 

它应该返回false。

如何使新的Date()与字符串位于同一时区。 (我假设字符串包含了当前时间在其之前或之后需要告知的所有信息。)

2 个答案:

答案 0 :(得分:3)

如果你要比较Unix时间戳,你不应该担心时区(见this answer为什么)。

您正在进行正确比较 - 您获得了true而不是false,因为这是正确的:

> new Date()
Wed Oct 16 2013 11:51:29 GMT-0400 (EDT)
> Date.parse("Wed, 16 Oct 2013") > new Date().getTime()
false
> Date.parse("Wed, 16 Oct 2013 00:00:00 GMT") > new Date().getTime()
false
> Date.parse("Wed, 16 Oct 2013 23:00:00 GMT") > new Date().getTime()
true

答案 1 :(得分:0)

您可以使用数据库返回的字符串创建一个新日期,并使用常用运算符进行比较:

var expirationDate = new Date("Wed, 16 Oct 2013 15:42:53 GMT");
var now = new Date();
alert(now > expirationDate);

JSFiddle