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?
            Asked
            
        
        
            Active
            
        
            Viewed 437 times
        
    -1
            
            
        - 
                    You can easily get the date and month etc. from a `Date` object. Where is your attempt at solving this on your own? – Nov 23 '18 at 12:51
- 
                    possible duplicate:https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript – Prashant Pimpale Nov 23 '18 at 12:52
- 
                    It's not a duplicate because I want to compare days only, not the full date. – abyrne85 Nov 23 '18 at 12:55
- 
                    i added a snippet to my post – Nov 23 '18 at 12:57
- 
                    1You can always set time to noon (or anything, just the same thing for all dates), and compare the results. – tevemadar Nov 23 '18 at 12:57
1 Answers
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);
}
