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

<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中获得两个日期之间的天数?


当前回答

更好的解决方案

忽略时间部分

如果两个日期相同,则返回0。

function dayDiff(firstDate, secondDate) { firstDate = new Date(firstDate); secondDate = new Date(secondDate); if (!isNaN(firstDate) && !isNaN(secondDate)) { firstDate.setHours(0, 0, 0, 0); //ignore time part secondDate.setHours(0, 0, 0, 0); //ignore time part var dayDiff = secondDate - firstDate; dayDiff = dayDiff / 86400000; // divide by milisec in one day console.log(dayDiff); } else { console.log("Enter valid date."); } } $(document).ready(function() { $('input[type=datetime]').datepicker({ dateFormat: "mm/dd/yy", changeMonth: true, changeYear: true }); $("#button").click(function() { dayDiff($('#first').val(), $('#second').val()); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <input type="datetime" id="first" value="12/28/2016" /> <input type="datetime" id="second" value="12/28/2017" /> <input type="button" id="button" value="Calculate">

其他回答

我也有同样的问题,但如果你在SQL查询上做的话会更好:

DateDiff(DAY, StartValue,GETDATE()) AS CountDays

查询将自动生成一个列CountDays

如果我们想计算我们的年龄,这是一个有点不同的答案

    {
      birthday: 'April 22, 1993',
      names: {
        first: 'Keith',
        last: 'Buckley'
      }
    },
    {
      birthday: 'January 3, 1975',
      names: {
        first: 'Larry',
        last: 'Heep'
      }
    },
    {
      birthday: 'February 12, 1944',
      names: {
        first: 'Linda',
        last: 'Bermeer'
      }
    }
  ];
const cleanPeople = people.map(function ({birthday, names:{first, last}}) {
      // birthday, age, fullName;
      const now = new Date();
      var age =  Math.floor(( Date.parse(now) - Date.parse(birthday)) / 31536000000);
      return {
        age,
        fullName:`${first} ${last}`
      }
    });
    console.log(cleanPeople);
    console.table(cleanPeople);

我在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;
};

Date.prototype.days =函数(到){ 返回Math.abs(Math.floor(to.getTime() / (3600 * 24 * 1000)) - Math.floor(this.getTime() / (3600 * 24 * 1000))) } console.log(新日期(“2014/05/20”)。天(新日期(2014/05/23)));// 3天 console.log(新日期(“2014/05/23”)。天(新日期(2014/05/20)));// 3天

从DatePicker小部件使用formatDate怎么样?您可以使用它来转换时间戳格式的日期(从01/01/1970开始的毫秒),然后做一个简单的减法。