例如,在输入框中给定两个日期:

<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>

<script>
  alert(datediff("day", first, second)); // what goes here?
</script>

如何在JavaScript中获得两个日期之间的天数?


当前回答

function timeDifference(date1, date2) { var oneDay = 24 * 60 * 60; // hours*minutes*seconds var oneHour = 60 * 60; // minutes*seconds var oneMinute = 60; // 60 seconds var firstDate = date1.getTime(); // convert to milliseconds var secondDate = date2.getTime(); // convert to milliseconds var seconds = Math.round(Math.abs(firstDate - secondDate) / 1000); //calculate the diffrence in seconds // the difference object var difference = { "days": 0, "hours": 0, "minutes": 0, "seconds": 0, } //calculate all the days and substract it from the total while (seconds >= oneDay) { difference.days++; seconds -= oneDay; } //calculate all the remaining hours then substract it from the total while (seconds >= oneHour) { difference.hours++; seconds -= oneHour; } //calculate all the remaining minutes then substract it from the total while (seconds >= oneMinute) { difference.minutes++; seconds -= oneMinute; } //the remaining seconds : difference.seconds = seconds; //return the difference object return difference; } console.log(timeDifference(new Date(2017,0,1,0,0,0),new Date()));

其他回答

Bookmarklet版本的其他答案,提示你两个日期:

javascript:(function() {
    var d = new Date(prompt("First Date or leave blank for today?") || Date.now());
    prompt("Days Between", Math.round(
        Math.abs(
            (d.getTime() - new Date(prompt("Date 2")).getTime())
                /(24*60*60*1000)
             )
        ));
})();

我在Angular中也遇到了同样的问题。我复制了一份,否则他会覆盖第一次约会。两个日期的时间都必须为00:00:00(显然)

 /*
* Deze functie gebruiken we om het aantal dagen te bereken van een booking.
* */
$scope.berekenDagen = function ()
{
    $scope.booking.aantalDagen=0;

    /*De loper is gelijk aan de startdag van je reservatie.
     * De copy is nodig anders overschijft angular de booking.van.
     * */
    var loper = angular.copy($scope.booking.van);

    /*Zolang de reservatie beschikbaar is, doorloop de weekdagen van je start tot einddatum.*/
    while (loper < $scope.booking.tot) {
        /*Tel een dag op bij je loper.*/
        loper.setDate(loper.getDate() + 1);
        $scope.booking.aantalDagen++;
    }

    /*Start datum telt natuurlijk ook mee*/
    $scope.booking.aantalDagen++;
    $scope.infomsg +=" aantal dagen: "+$scope.booking.aantalDagen;
};

我只有两个以毫秒为单位的时间戳,所以我必须用moment.js做一些额外的步骤来获得天数。

const getDaysDiff = (fromTimestamp, toTimestamp) => {
    // set timezone offset with utcOffset if needed
    let fromDate = moment(fromTimestamp).utcOffset(8);
    let toDate = moment(toTimestamp).utcOffset(8);
    // get the start moment of the day
    fromDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
    toDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
    let diffDays = toDate.diff(fromDate, 'days');

    return diffDays;
}

getDaysDiff(1528889400000, 1528944180000)// 1 

如果你想有一个DateArray日期试试这个:

<script>
        function getDates(startDate, stopDate) {
        var dateArray = new Array();
        var currentDate = moment(startDate);
        dateArray.push( moment(currentDate).format('L'));

        var stopDate = moment(stopDate);
        while (dateArray[dateArray.length -1] != stopDate._i) {
            dateArray.push( moment(currentDate).format('L'));
            currentDate = moment(currentDate).add(1, 'days');
        }
        return dateArray;
      }
</script>

调试片段

var start= $("#firstDate").datepicker("getDate");
var end= $("#SecondDate").datepicker("getDate");
var days = (end- start) / (1000 * 60 * 60 * 24);
 alert(Math.round(days));

Jsfiddle示例:)