日期比较在某些浏览器中无效 - Javascript

时间:2015-09-25 13:51:50

标签: javascript

我面临一些不寻常的问题。

var past = utils.stringToDate(past, 'dd-mm-yyyy', '-');
var today = new Date();
past.setHours(0, 0, 0, 0);
today.setHours(0, 0, 0, 0);

return today > past? true: false;

上面的代码用于设置标志,该标志用于决定用户的流量。现在的问题是,它在包括IE在内的大多数浏览器中工作,但在Windows上的Safari(在Safari,Mac中运行良好)和Opera中都失败了。

过去是我从服务器收到的日期,其值为27-09-2015

stringToDate 是一个以指定格式格式化日期的函数。

测试用例

past : 27-09-2015
today: 25-09-2015

上面的代码仍会在上述浏览器中返回true

所以问题是,浏览器在比较javascript中的日期对象方面是否存在差异?如果是,那么我应该注意哪些不太知名的案例?

此变量在整个生命周期中仅设置一次,并且不会在其他任何地方更新。

1 个答案:

答案 0 :(得分:0)

您可以比较它们为原型添加一个函数,如下所示:

let userMessageLabel.text = userMessage + "        "

然后使用它:

/*
 * Compares two Date objects numerically.
 *
 * @param date the Date to be compared.
 * @return the value of 0 if this Date is equal to the argument date; 
 * a value of -1 if this Date is numerically less than the argument date;
 * and a value of 1 if this Date is numerically greater than the argument date.
 */
Date.prototype.compareTo = function(date) {
    var d1_this = this.getTime(),
        d2_time = date.getTime();

    if (d1_this == d2_time) {
        return 0;
    } else if (d1_this < d2_time) {
        return -1;
    } else {
        return 1;
    }
}
相关问题