javascript中的日期比较无法正常工作

时间:2019-06-12 22:38:52

标签: javascript

我正在JavaScript代码中遇到这个奇怪的行为:-

var expirydate = item.get_item('ExpireDate');
alert("expirydate = "+ expirydate);

var modifieddate = item.get_item('Modified');
alert("modifieddate = "+ modifieddate);

var currentdate = new Date();
alert("currentdate = "+currentdate);

expirydate.setDate(expirydate.getDate() + 1);
var expiredperiod = expirydate;
alert("expired period = " + expiredperiod );

其中上面返回了以下内容:-

expirydate = Mon Jun 10 2019 00:00:00 GMT+0100 (British Summer Time)

modifieddate = Mon Jun 10 2019 22:12:59 GMT+0100 (British Summer Time)

currentdate = Wed Jun 12 2019 23:33:07 GMT+0100 (British Summer Time)

expired period = Tue Jun 11 2019 00:00:00 GMT+0100 (British Summer Time)

但是我有这个比较

if (expirydate != null && modifieddate  < expirydate && currentdate > expiredperiod )

在上述情况下,if语句通过了..尽管我可以看到在我的情况下,modifieddate的{​​{1}}大于Mon Jun 10 2019 22:12:59 GMT+0100 (British Summer Time)的{​​{1}}这会导致expirydate语句失败..所以不确定为什么我的Mon Jun 10 2019 00:00:00 GMT+0100 (British Summer Time)语句通过了吗?

这是完整的代码

if

我为到期日期添加了另一个变量,如下所示:-

if

2 个答案:

答案 0 :(得分:2)

我的意思是您尝试比较无效的日期格式,不是吗?尝试在new Date周围添加item.getItem(...)

var expirydate = new Date (item.get_item('ExpireDate'));
alert("expirydate = "+ expirydate);

var modifieddate = new Date(item.get_item('Modified'));
alert("modifieddate = "+ modifieddate);

var currentdate = new Date();
alert("currentdate = "+currentdate);

expirydate.setDate(expirydate.getDate() + 1);
var expiredperiod = expirydate;
alert("expired period = " + expiredperiod );

答案 1 :(得分:2)

您在此处输出expirydate

var expirydate = item.get_item('ExpireDate');
alert("expirydate = "+ expirydate);

但是,然后在比较中使用它之前,请在此处更改expirydate

expirydate.setDate(expirydate.getDate() + 1);

因此,您的“警报”输出会误导您

你以为你在做什么

expirydate = new Date('Mon Jun 10 2019 00:00:00 GMT+0100');
modifieddate = new Date('Mon Jun 10 2019 22:12:59 GMT+0100');
currentdate = new Date('Wed Jun 12 2019 23:33:07 GMT+0100');
expiredperiod = new Date('Tue Jun 11 2019 00:00:00 GMT+0100');
console.log(expirydate != null && modifieddate  < expirydate && currentdate > expiredperiod )

您的代码实际上在做什么

//expirydate = new Date('Mon Jun 10 2019 00:00:00 GMT+0100');
modifieddate = new Date('Mon Jun 10 2019 22:12:59 GMT+0100');
currentdate = new Date('Wed Jun 12 2019 23:33:07 GMT+0100');
expiredperiod = new Date('Tue Jun 11 2019 00:00:00 GMT+0100');
expirydate = expiredperiod // <==== this is the key to your issue
console.log(expirydate != null && modifieddate  < expirydate && currentdate > expiredperiod )

现在,关于您的后期修改

确实

item.get_item('ExpireDate')

返回Date对象?

如果是这样,那么

        var expirydate = item.get_item('ExpireDate');
        var expirydate2 = item.get_item('ExpireDate');

将导致这两个变量都引用同一对象

更改一个,您更改另一个...

尝试

var expirydate = item.get_item('ExpireDate');
var expiredperiod = new Date(expiryDate);
expiredperiod.setDate(expiredperiod.getDate()+1);