-1

I'm trying to compare two dates by day in javascript. Comparing dates is fine, but I want just compare them by day and ignore the time of day. Is this possible without relying on a library like momentjs?

abyrne85
  • 1,370
  • 16
  • 33

1 Answers1

2

Here is a snippet that compares dates without time:

   var today = new Date();
    today.setHours(0, 0, 0, 0);
    d = new Date(my_value); 
    d.setHours(0, 0, 0, 0);

    if(d >= today){ 
        alert(d is greater than or equal to current date);
    }

And here is a function that will give you the exact difference between two days:

function daysBetween(first, second) {

    // Copy date parts of the timestamps, discarding the time parts.
    var one = new Date(first.getFullYear(), first.getMonth(), first.getDate());
    var two = new Date(second.getFullYear(), second.getMonth(), second.getDate());

    // Do the math.
    var millisecondsPerDay = 1000 * 60 * 60 * 24;
    var millisBetween = two.getTime() - one.getTime();
    var days = millisBetween / millisecondsPerDay;

    // Round down.
    return Math.floor(days);
}