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

前端 未结 16 2385
北海茫月
北海茫月 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 03:50

    Depending on your needs, this function will calculate the difference between the 2 days, and return a result in days decimal.

    // This one returns a signed decimal. The sign indicates past or future.
    
    this.getDateDiff = function(date1, date2) {
        return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24);
    }
    
    // This one always returns a positive decimal. (Suggested by Koen below)
    
    this.getDateDiff = function(date1, date2) {
        return Math.abs((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24));
    }
    

提交回复
热议问题