Javascript compare two dates to get a difference

后端 未结 6 2100
长情又很酷
长情又很酷 2020-12-12 04:24

I am trying to compare two different dates to see if the date inputted is after 7 days of todays date. I have done a bit of googling and come up with this:

f         


        
6条回答
  •  长情又很酷
    2020-12-12 05:15

    If you are comparing dates and don't want to include time, you can use something like:

    // dateString is format DD-MM-YYYY
    function isMoreThan7DaysHence(dateString) {
    
        // Turn string into a date object at 00:00:00
        var t = dateString.split('-');
        var d0 = new Date(t[2], --t[1], t[0]);
    
        // Create a date for 7 days hence at 00:00:00
        var d1 = new Date();
        d1.setHours(0, 0, 0, 0);
        d1.setDate(d1.getDate() + 7);
    
        return d0 >= d1;
    }
    

    Note that the hours for today's date must be zeroed.

提交回复
热议问题