How do I get the difference between two Dates in JavaScript?

前端 未结 16 2644
北海茫月
北海茫月 2020-11-22 03:03

I\'m creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date.

16条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 04:08

    If you don't care about the time component, you can use .getDate() and .setDate() to just set the date part.

    So to set your end date to 2 weeks after your start date, do something like this:

    function GetEndDate(startDate)
    {
        var endDate = new Date(startDate.getTime());
        endDate.setDate(endDate.getDate()+14);
        return endDate;
    }
    

    To return the difference (in days) between two dates, do this:

    function GetDateDiff(startDate, endDate)
    {
        return endDate.getDate() - startDate.getDate();
    }
    

    Finally, let's modify the first function so it can take the value returned by 2nd as a parameter:

    function GetEndDate(startDate, days)
    {
        var endDate = new Date(startDate.getTime());
        endDate.setDate(endDate.getDate() + days);
        return endDate;
    }
    

提交回复
热议问题