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

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


当前回答

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

Jsfiddle示例:)

其他回答

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

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

查询将自动生成一个列CountDays

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

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

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

return dayCount; 
}

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

更好的解决方案

忽略时间部分

如果两个日期相同,则返回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">

我使用下面的代码来试验新闻帖子的发布日期功能。我根据发布日期和当前日期计算分钟、小时、天或年。

var startDate= new Date("Mon Jan 01 2007 11:00:00");
var endDate  =new Date("Tue Jan 02 2007 12:50:00");
var timeStart = startDate.getTime();
var timeEnd = endDate.getTime();
var yearStart = startDate.getFullYear();
var yearEnd   = endDate.getFullYear();
if(yearStart == yearEnd)
 {
  var hourDiff = timeEnd - timeStart; 
  var secDiff = hourDiff / 1000;
  var minDiff = hourDiff / 60 / 1000; 
  var hDiff = hourDiff / 3600 / 1000; 
  var myObj = {};
  myObj.hours = Math.floor(hDiff);
  myObj.minutes = minDiff  
  if(myObj.hours >= 24)
   {
    console.log(Math.floor(myObj.hours/24) + "day(s) ago")
   } 
 else if(myObj.hours>0)
  {
   console.log(myObj.hours +"hour(s) ago")
  }
 else
  {
   console.log(Math.abs(myObj.minutes) +"minute(s) ago")
  }
}
else
{
var yearDiff = yearEnd - yearStart;
console.log( yearDiff +" year(s) ago");
}

这个答案基于另一个答案(链接在最后),是关于两个日期之间的差异。 你可以看到它是如何工作的,因为它很简单,它还包括将差异分成 时间单位(我做的一个函数)并转换为UTC以停止时区问题。

function date_units_diff(a, b, unit_amounts) { var split_to_whole_units = function (milliseconds, unit_amounts) { // unit_amounts = list/array of amounts of milliseconds in a // second, seconds in a minute, etc., for example "[1000, 60]". time_data = [milliseconds]; for (i = 0; i < unit_amounts.length; i++) { time_data.push(parseInt(time_data[i] / unit_amounts[i])); time_data[i] = time_data[i] % unit_amounts[i]; }; return time_data.reverse(); }; if (unit_amounts == undefined) { unit_amounts = [1000, 60, 60, 24]; }; var utc_a = new Date(a.toUTCString()); var utc_b = new Date(b.toUTCString()); var diff = (utc_b - utc_a); return split_to_whole_units(diff, unit_amounts); } // Example of use: var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2); document.write("In difference: 0 days, 1 hours, 2 minutes.".replace( /0|1|2/g, function (x) {return String( d[Number(x)] );} ));

我上面的代码是如何工作的

日期/时间差异,以毫秒为单位,可以使用date对象计算:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

然后算出这个差值的秒数,将其除以1000进行换算 毫秒到秒,然后将结果更改为整数(整数)以删除 毫秒数(小数的小数部分):var seconds = parseInt(diff/1000)。 此外,我可以使用相同的过程获得更长的时间单位,例如: -(整)分钟,秒除以60,结果变为整数, —hours,分钟除以60,返回结果为整数。

我创建了一个函数来完成这个过程,把差值分成 整个时间单位,命名为split_to_whole_units,演示如下:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

这个答案是基于另一个答案的。