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

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


当前回答

要计算两个给定日期之间的天数,可以使用以下代码。我在这里使用的日期是2016年1月1日和2016年12月31日

var day_start = new日期(“2016年1月1日”); var day_end =新的日期(“2016年12月31日”); Var total_days = (day_end - day_start) / (1000 * 60 * 60 * 24); . getelementbyid(“演示”)。innerHTML = Math.round(total_days); <h3>天之间的给定日期</h3> < p id = "演示" > < / p >

其他回答

下面是datediff的快速实现,作为解决问题的概念证明。它依赖于这样一个事实,即您可以通过减去两个日期之间经过的毫秒,这将它们强制转换为原始数字值(自1970年初以来的毫秒)。

/** * Take the difference between the dates and divide by milliseconds per day. * Round to nearest whole number to deal with DST. */ function datediff(first, second) { return Math.round((second - first) / (1000 * 60 * 60 * 24)); } /** * new Date("dateString") is browser-dependent and discouraged, so we'll write * a simple parse function for U.S. date format (which does no error checking) */ function parseDate(str) { var mdy = str.split('/'); return new Date(mdy[2], mdy[0] - 1, mdy[1]); } alert(datediff(parseDate(first.value), parseDate(second.value))); <input id="first" value="1/1/2000"/> <input id="second" value="1/1/2001"/>

You should be aware that the "normal" Date APIs (without "UTC" in the name) operate in the local timezone of the user's browser, so in general you could run into issues if your user is in a timezone that you don't expect, and your code will have to deal with Daylight Saving Time transitions. You should carefully read the documentation for the Date object and its methods, and for anything more complicated, strongly consider using a library that offers more safe and powerful APIs for date manipulation.

数字和日期——MDN JavaScript指南 日期——MDN JavaScript参考

同样,出于说明的目的,为了简洁起见,该代码段对窗口对象使用了命名访问,但在生产中应该使用getElementById之类的标准化api,或者更有可能使用一些UI框架。

这可能不是最优雅的解决方案,但我认为它似乎用一段相对简单的代码就回答了这个问题。你不能用这样的词吗?

function dayDiff(startdate, enddate) {
  var dayCount = 0;

  while(enddate >= startdate) {
    dayCount++;
    startdate.setDate(startdate.getDate() + 1);
  }

return dayCount; 
}

这是假设您将日期对象作为参数传递。

   function validateDate() {
        // get dates from input fields
        var startDate = $("#startDate").val();
        var endDate = $("#endDate").val();
        var sdate = startDate.split("-");
        var edate = endDate.split("-");
        var diffd = (edate[2] - sdate[2]) + 1;
        var leap = [ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
        var nonleap = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
        if (sdate[0] > edate[0]) {
            alert("Please enter End Date Year greater than Start Date Year");
            document.getElementById("endDate").value = "";
            diffd = "";
        } else if (sdate[1] > edate[1]) {
            alert("Please enter End Date month greater than Start Date month");
            document.getElementById("endDate").value = "";
            diffd = "";
        } else if (sdate[2] > edate[2]) {
            alert("Please enter End Date greater than Start Date");
            document.getElementById("endDate").value = "";
            diffd = "";
        } else {
            if (sdate[0] / 4 == 0) {
                while (sdate[1] < edate[1]) {
                    diffd = diffd + leap[sdate[1]++];
                }
            } else {
                while (sdate[1] < edate[1]) {
                    diffd = diffd + nonleap[sdate[1]++];
                }
            }
            document.getElementById("numberOfDays").value = diffd;
        }
    }

计算两个日期之间天数的简单方法是去掉它们的时间分量,即将小时、分钟、秒和毫秒设置为0,然后减去它们的时间,用一天的毫秒值来计算。

var firstDate= new Date(firstDate.setHours(0,0,0,0));
var secondDate= new Date(secondDate.setHours(0,0,0,0));
var timeDiff = firstDate.getTime() - secondDate.getTime();
var diffDays =timeDiff / (1000 * 3600 * 24);

试试这个

let today = new Date(). toisostring()。片(0,10) const startDate = '2021-04-15'; const endDate = today; const diffInMs = new Date(endDate) - new Date(startDate) const diffInDays = diffInMs / (1000 * 60 * 60 * 24); alert(diffInDays);