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

前端 未结 16 2354
北海茫月
北海茫月 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条回答
  • 2020-11-22 04:06
    <html>
    <head>
    <script>
    function dayDiff()
    {
         var start = document.getElementById("datepicker").value;
         var end= document.getElementById("date_picker").value;
         var oneDay = 24*60*60*1000; 
         var firstDate = new Date(start);
         var secondDate = new Date(end);    
         var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
        document.getElementById("leave").value =diffDays ;
     }
    </script>
    </head>
    <body>
    <input type="text" name="datepicker"value=""/>
    <input type="text" name="date_picker" onclick="function dayDiff()" value=""/>
    <input type="text" name="leave" value=""/>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 04:08

    Thanks @Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin. Here's the simplified end solution:

        // don't update end date if there's already an end date but not an old start date
        if (!oldEnd || oldBegin) {
            var selectedDateSpan = 1800000; // 30 minutes
            if (oldEnd) {
                selectedDateSpan = oldEnd - oldBegin;
            }
    
           newEnd = new Date(newBegin.getTime() + selectedDateSpan));
        }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-22 04:08

    If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.

    moment(endDate).diff(moment(beginDate), 'days');
    

    Additional details can be found in the moment.js page

    Cheers, Miguel

    0 讨论(0)
提交回复
热议问题