Date comparison does not work in some browsers - Javascript

I ran into some unusual problem.

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;

The above code is used to set the flag, and this flag is used to determine the user flow. Now the problem is that it works in most browsers, including IE, but does not work in Safari on windows (works fine in Safari, Mac) and Opera.

past is the date I get from the server, and the value 27-09-2015.

stringToDate is a function that formats the date in the specified format.

Test case

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

Even higher, the code returns truein the specified browsers.

So the question is, is there any difference in browsers when comparing date objects in javascript, and if so, which lesser-known cases should I know?

.

+4
1

, :

/*
 * 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;
    }
}

:

var date1 = new Date(), date2 = new Date(); // init vars
date1.compareTo(date2); // or
date2.compareTo(date1);
0

Source: https://habr.com/ru/post/1609000/


All Articles