Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing dates only by year, month and date?

Say we have 2 Date objects in Javascript;

var d1 = new Date('...');
var d2 = new Date('...');

We do a comparison:

d1 < d2;

This comparison will always take into account hours, minutes, seconds.

I want it to only take into account the year, month and date for comparison.

What's the easiest way to do this?

jQuery is allowed aswell.

like image 952
Tool Avatar asked Dec 01 '25 06:12

Tool


2 Answers

Reset the hours, minutes, seconds, and milliseconds:

var d1 = new Date();
d1.setHours(0);
d1.setMinutes(0);
d1.setSeconds(0);
d1.setMilliseconds(0);

Or using setHours, which is less verbose:

var d1= new Date();
d1.setHours(0, 0, 0, 0);

And finally, to compare if the resulting Dates are the same use getTime():

d1.getTime() == d2.getTime()
like image 88
João Silva Avatar answered Dec 03 '25 19:12

João Silva


As an algebraic solution, you could just run a bit of math:

function sameDay(d1, d2) {
    return d1 - d1 % 86400000 == d2 - d2 % 86400000
}

The equation actually breaks down as:

function sameDay(d1, d2) {
    var d1HMS, //hours, minutes, seconds & milliseconds
        d2HMS,
        d1Day,
        d2Day,
        result;
    //d1 and d2 will be implicitly cast to Number objects
    //this is to be explicit
    d1 = +d1;
    d2 = +d2;
    //1000 milliseconds in a second
    //60 seconds in a minute
    //60 minutes in an hour
    //24 hours in a day
    //modulus used to find remainder of hours, minutes, seconds, and milliseconds
    //after being divided into days
    d1HMS = d1 % (1000 * 60 * 60 * 24);
    d2HMS = d2 % (1000 * 60 * 60 * 24);
    //remove the remainder to find the timestamp for midnight of that day
    d1Day = d1 - d1HMS;
    d2Day = d2 - d2HMS;
    //compare the results
    result = d1Day == d2Day;
    return result;
}

This has the advantage of not losing data on the original Date objects, as setHours and the like will modify the referenced object.

Alternatively, a safe sameDay function using setHours could be written as:

function sameDay(d1, d2) {
    var a,
        b;
    a = new Date(+d1);
    b = new Date(+d2);
    a.setHours(0, 0, 0, 0);
    b.setHours(0, 0, 0, 0);
    return +a == +b;
}
like image 41
zzzzBov Avatar answered Dec 03 '25 19:12

zzzzBov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!