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

时间:2022-07-13 21:30:38

How do I get the number of days between two dates in JavaScript? For example, given two dates in input boxes:

如何在JavaScript中获得两个日期之间的天数?例如,在输入框中给定两个日期:

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

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

31 个解决方案

#1


313  

Here is a quick and dirty implementation of datediff, as a proof of concept to solve the problem as presented in the question. It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).

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

// 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]);
}

function datediff(first, second) {
    // Take the difference between the dates and divide by milliseconds per day.
    // Round to nearest whole number to deal with DST.
    return Math.round((second-first)/(1000*60*60*24));
}

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.

你应该意识到“正常”日期api(没有“UTC”名称)在用户的浏览器的本地时区,所以通常你可以遇到的问题如果你的用户是你别指望在一个时区,和您的代码将不得不处理夏令时转换。您应该仔细阅读Date对象及其方法的文档,如果需要更复杂的东西,请考虑使用为日期操作提供更安全、更强大的api的库。

Also, for illustration purposes, the snippet uses named access on the window object for brevity, but in production you should use standardized APIs like getElementById, or more likely, some UI framework.

同样,为了便于演示,代码片段在窗口对象上使用了命名访问,但在生产中,您应该使用标准化的api,比如getElementById,或者更可能是一些UI框架。

#2


175  

As of this writing, only one of the other answers correctly handles DST (daylight saving time) transitions. Here are the results on a system located in California:

在撰写本文时,其他答案中只有一个正确地处理了DST(夏令时)转换。以下是加利福尼亚的一个系统的结果:

                                        1/1/2013- 3/10/2013- 11/3/2013-
User       Formula                      2/1/2013  3/11/2013  11/4/2013  Result
---------  ---------------------------  --------  ---------  ---------  ---------
Miles                   (d2 - d1) / N   31        0.9583333  1.0416666  Incorrect
some         Math.floor((d2 - d1) / N)  31        0          1          Incorrect
fuentesjr    Math.round((d2 - d1) / N)  31        1          1          Correct
toloco     Math.ceiling((d2 - d1) / N)  31        1          2          Incorrect

N = 86400000

Although Math.round returns the correct results, I think it's somewhat clunky. Instead, by explicitly accounting for changes to the UTC offset when DST begins or ends, we can use exact arithmetic:

虽然数学。round返回的结果是正确的,我认为有点笨拙。相反,通过显式地计算当DST开始或结束时UTC偏移量的变化,我们可以使用精确的算术:

function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

function daysBetween(startDate, endDate) {
    var millisecondsPerDay = 24 * 60 * 60 * 1000;
    return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}

alert(daysBetween($('#first').val(), $('#second').val()));

Explanation

JavaScript date calculations are tricky because Date objects store times internally in UTC, not local time. For example, 3/10/2013 12:00 AM Pacific Standard Time (UTC-08:00) is stored as 3/10/2013 8:00 AM UTC, and 3/11/2013 12:00 AM Pacific Daylight Time (UTC-07:00) is stored as 3/11/2013 7:00 AM UTC. On this day, midnight to midnight local time is only 23 hours in UTC!

JavaScript日期计算很棘手,因为日期对象在UTC内部存储时间,而不是本地时间。例如,3/10/2013太平洋标准时间(UTC-08:00)存储为3/10/2013上午8:00;3/11/2013太平洋夏令时(UTC-07:00)存储为3/11/2013上午7:00。在这一天,从午夜到午夜当地时间在UTC只有23小时!

Although a day in local time can have more or less than 24 hours, a day in UTC is always exactly 24 hours.1 The daysBetween method shown above takes advantage of this fact by first calling treatAsUTC to adjust both local times to midnight UTC, before subtracting and dividing.

虽然在当地时间的一天可以有超过或少于24小时,但在UTC的一天总是完全24小时。上面所示的daysBetween方法利用了这一事实,首先调用treatAsUTC来调整两个本地时间到UTC午夜,然后减去和分割。

1. JavaScript ignores leap seconds.

1。JavaScript忽略了闰秒。

#3


102  

The easiest way to get the difference between two dates:

最简单的方法来区分两个日期:

var diff =  Math.floor(( Date.parse(str2) - Date.parse(str1) ) / 86400000); 

You get the difference days (or NaN if one or both could not be parsed). The parse date gived the result in milliseconds and to get it by day you have to divided it by 24 * 60 * 60 * 1000

您将获得差异日(或NaN,如果一个或两个都不能被解析)。解析日期以毫秒为单位给出结果,要在一天之内得到结果,必须将其除以24 * 60 * 60 * 1000

If you want it divided by days, hours, minutes, seconds and milliseconds:

如果你想要它除以天、小时、分钟、秒和毫秒:

function dateDiff( str1, str2 ) {
    var diff = Date.parse( str2 ) - Date.parse( str1 ); 
    return isNaN( diff ) ? NaN : {
        diff : diff,
        ms : Math.floor( diff            % 1000 ),
        s  : Math.floor( diff /     1000 %   60 ),
        m  : Math.floor( diff /    60000 %   60 ),
        h  : Math.floor( diff /  3600000 %   24 ),
        d  : Math.floor( diff / 86400000        )
    };
}

Here is my refactored version of James version:

以下是我重构的詹姆斯版本:

function mydiff(date1,date2,interval) {
    var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
    date1 = new Date(date1);
    date2 = new Date(date2);
    var timediff = date2 - date1;
    if (isNaN(timediff)) return NaN;
    switch (interval) {
        case "years": return date2.getFullYear() - date1.getFullYear();
        case "months": return (
            ( date2.getFullYear() * 12 + date2.getMonth() )
            -
            ( date1.getFullYear() * 12 + date1.getMonth() )
        );
        case "weeks"  : return Math.floor(timediff / week);
        case "days"   : return Math.floor(timediff / day); 
        case "hours"  : return Math.floor(timediff / hour); 
        case "minutes": return Math.floor(timediff / minute);
        case "seconds": return Math.floor(timediff / second);
        default: return undefined;
    }
}

#4


70  

I recommend using the moment.js library (http://momentjs.com/docs/#/displaying/difference/). It handles daylight savings time correctly and in general is great to work with.

我推荐使用这个时刻。js库(http://momentjs.com/docs/ /显示/ /)差异。它正确地处理日光节约时间,而且一般来说,它很好用。

Example:

例子:

var start = moment("2013-11-03");
var end = moment("2013-11-04");
end.diff(start, "days")
1

#5


39  

I would go ahead and grab this small utility and in it you will find functions to this for you. Here's a short example:

我来获取这个小工具,在它里面你可以找到它的函数。这是一个简短的例子:

        <script type="text/javascript" src="date.js"></script>
        <script type="text/javascript">
            var minutes = 1000*60;
            var hours = minutes*60;
            var days = hours*24;

            var foo_date1 = getDateFromFormat("02/10/2009", "M/d/y");
            var foo_date2 = getDateFromFormat("02/12/2009", "M/d/y");

            var diff_date = Math.round((foo_date2 - foo_date1)/days);
            alert("Diff date is: " + diff_date );
        </script>

#6


13  

Using Moment.js

使用Moment.js

var future = moment('05/02/2015');
var start = moment('04/23/2015');
var d = future.diff(start, 'days'); // 9
console.log(d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>

#7


8  

Date values in JS are datetime values.

JS中的日期值是datetime值。

So, direct date computations are inconsistent:

因此,直接日期计算是不一致的:

(2013-11-05 00:00:00) - (2013-11-04 10:10:10) < 1 day

for example we need to convert de 2nd date:

例如,我们需要转换到第二个日期:

(2013-11-05 00:00:00) - (2013-11-04 00:00:00) = 1 day

the method could be truncate the mills in both dates:

该方法可以在两个日期截断铣刀:

var date1 = new Date('2013/11/04 00:00:00');
var date2 = new Date('2013/11/04 10:10:10'); //less than 1
var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates
console.log(daysDiff);

date2 = new Date('2013/11/05 00:00:00'); //1

var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates
console.log(daysDiff);

#8


7  

To Calculate days between 2 given dates you can use the following code.Dates I use here are Jan 01 2016 and Dec 31 2016

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

var day_start = new Date("Jan 01 2016");
var day_end = new Date("Dec 31 2016");
var total_days = (day_end - day_start) / (1000 * 60 * 60 * 24);
document.getElementById("demo").innerHTML = Math.round(total_days);
<h3>DAYS BETWEEN GIVEN DATES</h3>
<p id="demo"></p>

#9


6  

What about using formatDate from DatePicker widget? You could use it to convert the dates in timestamp format (milliseconds since 01/01/1970) and then do a simple subtraction.

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

#10


6  

I found this question when I want do some calculate on two date, but the date have hours and minutes value, I modified @michael-liu 's answer to fit my requirement, and it passed my test.

当我想计算两个日期时,我发现了这个问题,但是这个日期有小时和分钟的值,我修改了@michael-liu的答案以符合我的要求,它通过了我的测试。

diff days 2012-12-31 23:00 and 2013-01-01 01:00 should equal 1. (2 hour) diff days 2012-12-31 01:00 and 2013-01-01 23:00 should equal 1. (46 hour)

2012-12-31 23:00和2013-01-01 01:00应该等于1。(2小时)2012-12-31 01:00和2013-01-01 23:00应该等于1。(46个小时)

function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

var millisecondsPerDay = 24 * 60 * 60 * 1000;
function diffDays(startDate, endDate) {
    return Math.floor(treatAsUTC(endDate) / millisecondsPerDay) - Math.floor(treatAsUTC(startDate) / millisecondsPerDay);
}

#11


6  

I think the solutions aren't correct 100% I would use ceil instead of floor, round will work but it isn't the right operation.

我认为解决方案并不是100%的正确,我将使用ceil而不是floor, round会起作用,但它不是正确的操作。

function dateDiff(str1, str2){
    var diff = Date.parse(str2) - Date.parse(str1); 
    return isNaN(diff) ? NaN : {
        diff: diff,
        ms: Math.ceil(diff % 1000),
        s: Math.ceil(diff / 1000 % 60),
        m: Math.ceil(diff / 60000 % 60),
        h: Math.ceil(diff / 3600000 % 24),
        d: Math.ceil(diff / 86400000)
    };
}

#12


6  

It is possible to calculate a full proof days difference between two dates resting across different TZs using the following formula:

使用以下公式,可以计算出不同TZs上的两个日期之间的完整证明日差异:

var start = new Date('10/3/2015');
var end = new Date('11/2/2015');
var days = (end - start) / 1000 / 60 / 60 / 24;
console.log(days);
// actually its 30 ; but due to daylight savings will show 31.0xxx
// which you need to offset as below
days = days - (end.getTimezoneOffset() - start.getTimezoneOffset()) / (60 * 24);
console.log(days);

#13


5  

Better to get rid of DST, Math.ceil, Math.floor etc. by using UTC times:

最好摆脱DST,数学。装天花板,数学。使用UTC时间:

var firstDate = Date.UTC(2015,01,2);
var secondDate = Date.UTC(2015,04,22);
var diff = Math.abs((firstDate.valueOf() 
    - secondDate.valueOf())/(24*60*60*1000));

This example gives difference 109 days. 24*60*60*1000 is one day in milliseconds.

这个例子给出了109天的差值。24*60*60*1000是一天的毫秒数。

#14


5  

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

jsfiddle example :)

jsfiddle例子:)

#15


4  

Be careful when using milliseconds.

使用毫秒时要小心。

The date.getTime() returns milliseconds and doing math operation with milliseconds requires to include

gettime()返回毫秒,需要使用毫秒执行数学操作

  • Daylight Saving Time (DST)
  • 夏令时(DST)
  • checking if both dates have the same time (hours, minutes, seconds, milliseconds)
  • 检查两个日期是否有相同的时间(小时、分钟、秒、毫秒)
  • make sure what behavior of days diff is required: 19 September 2016 - 29 September 2016 = 1 or 2 days difference?
  • 确定需要的天数差异行为:2016年9月19日- 2016年9月29日= 1天或2天的差异?

The example from comment above is the best solution I found so far https://*.com/a/11252167/2091095 . But use +1 to its result if you want the to count all days involved.

上面注释中的示例是我到目前为止找到的最佳解决方案:https://*.com/a/11252167/2091095。但是如果您想要计算所有涉及的天数的话,可以使用+1作为结果。

function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

function daysBetween(startDate, endDate) {
    var millisecondsPerDay = 24 * 60 * 60 * 1000;
    return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}

var diff = daysBetween($('#first').val(), $('#second').val()) + 1;

#16


4  

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()));

#17


4  

Date.prototype.days = function(to) {
  return Math.abs(Math.floor(to.getTime() / (3600 * 24 * 1000)) - Math.floor(this.getTime() / (3600 * 24 * 1000)))
}


console.log(new Date('2014/05/20').days(new Date('2014/05/23'))); // 3 days

console.log(new Date('2014/05/23').days(new Date('2014/05/20'))); // 3 days

#18


3  

This may not be the most elegant solution, but it seems to answer the question with a relatively simple bit of code, I think. Can't you use something like this:

这可能不是最优雅的解决方案,但我认为它似乎用相对简单的代码来回答这个问题。你不能用这样的东西:

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

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

return dayCount; 
}

This is assuming you are passing date objects as parameters.

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

#19


3  

I had the same issue in Angular. I do the copy because else he will overwrite the first date. Both dates must have time 00:00:00 (obviously)

我在角度上也有同样的问题。我做这个拷贝,因为他会重写第一次约会。两个日期必须都有时间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;
};

#20


3  

If you have two unix timestamps, you can use this function (made a little more verbose for the sake of clarity):

如果您有两个unix时间戳,您可以使用这个函数(为了清晰起见,可以更详细地说明):

// Calculate number of days between two unix timestamps
// ------------------------------------------------------------
var daysBetween = function(timeStampA, timeStampB) {
    var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
    var firstDate = new Date(timeStampA * 1000);
    var secondDate = new Date(timeStampB * 1000);
    var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
    return diffDays;
};

Example:

例子:

daysBetween(1096580303, 1308713220); // 2455

#21


3  

I used below code to experiment the posting date functionality for a news post.I calculate the minute or hour or day or year based on the posting date and current date.

我用下面的代码来测试一个新闻帖子的发布日期功能。我根据投寄日期及现时日期计算每一分钟或一小时或一天或一年。

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");
}

#22


3  

if you wanna have an DateArray with dates try this:

如果你想要一个带有日期的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>

DebugSnippet

DebugSnippet

#23


2  

function formatDate(seconds, dictionary) {
    var foo = new Date;
    var unixtime_ms = foo.getTime();
    var unixtime = parseInt(unixtime_ms / 1000);
    var diff = unixtime - seconds;
    var display_date;
    if (diff <= 0) {
        display_date = dictionary.now;
    } else if (diff < 60) {
        if (diff == 1) {
            display_date = diff + ' ' + dictionary.second;
        } else {
            display_date = diff + ' ' + dictionary.seconds;
        }
    } else if (diff < 3540) {
        diff = Math.round(diff / 60);
        if (diff == 1) {
            display_date = diff + ' ' + dictionary.minute;
        } else {
            display_date = diff + ' ' + dictionary.minutes;
        }
    } else if (diff < 82800) {
        diff = Math.round(diff / 3600);
        if (diff == 1) {
            display_date = diff + ' ' + dictionary.hour;
        } else {
            display_date = diff + ' ' + dictionary.hours;
        }
    } else {
        diff = Math.round(diff / 86400);
        if (diff == 1) {
            display_date = diff + ' ' + dictionary.day;
        } else {
            display_date = diff + ' ' + dictionary.days;
        }
    }
    return display_date;
}

#24


2  

const startDate = '2017-11-08';
const endDate   = '2017-10-01';
const timeDiff  = (new Date(startDate)) - (new Date(endDate));
const days      = timeDiff / (1000 * 60 * 60 * 24)
  1. Set start date
  2. 设置开始日期
  3. Set end date
  4. 设置结束日期
  5. Calculate difference
  6. 计算的区别
  7. Convert milliseconds to days
  8. 毫秒为单位转换为天

#25


1  

If you want a solution that works like the moment.js answers without the library overhead, you can use this component I wrote.

如果你想要一个像现在这样的解决方案。js回答不需要占用库开销,您可以使用我编写的这个组件。

For getting days:

让天:

var date1 = new Date('January 24, 1984 09:41:00');
var date2 = new Date('June 29, 2007 18:45:10');

var numDays = dateDiff(date1, date2, 'days');

In addition to calculating the number of days between two dates it can also calculate all the other standard time units (seconds, hours, weeks, months, etc.).

除了计算两个日期之间的天数之外,它还可以计算所有其他的标准时间单位(秒、小时、周、月等)。

To use the dateDiff() method you can import the component.

要使用dateDiff()方法,可以导入组件。

#26


1  

The simple way to calculate days between two dates is to remove both of their time component i.e. setting hours, minutes, seconds and milliseconds to 0 and then subtracting their time and diving it with milliseconds worth of one day.

计算两个日期之间的天数的简单方法是去掉它们的时间成分,即将小时、分钟、秒和毫秒设置为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);

#27


1  

A Better Solution by

一个更好的解决方案,

Ignoring time part

忽略时间的一部分

it will return 0 if both the dates are same.

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

#28


0  

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

#29


0  

You can use UnderscoreJS for formatting and calculating difference.

您可以使用UnderscoreJS进行格式化和计算差异。

Demo https://jsfiddle.net/sumitridhal/8sv94msp/

演示https://jsfiddle.net/sumitridhal/8sv94msp/

 var startDate = moment("2016-08-29T23:35:01");
var endDate = moment("2016-08-30T23:35:01");  
  

console.log(startDate);
console.log(endDate);

var resultHours = endDate.diff(startDate, 'hours', true);

document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(resultHours));
body { white-space: pre; font-family: monospace; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>

#30


0  

Bookmarklet version of other answers, prompting you for both dates:

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)
             )
        ));
})();

#1


313  

Here is a quick and dirty implementation of datediff, as a proof of concept to solve the problem as presented in the question. It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).

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

// 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]);
}

function datediff(first, second) {
    // Take the difference between the dates and divide by milliseconds per day.
    // Round to nearest whole number to deal with DST.
    return Math.round((second-first)/(1000*60*60*24));
}

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.

你应该意识到“正常”日期api(没有“UTC”名称)在用户的浏览器的本地时区,所以通常你可以遇到的问题如果你的用户是你别指望在一个时区,和您的代码将不得不处理夏令时转换。您应该仔细阅读Date对象及其方法的文档,如果需要更复杂的东西,请考虑使用为日期操作提供更安全、更强大的api的库。

Also, for illustration purposes, the snippet uses named access on the window object for brevity, but in production you should use standardized APIs like getElementById, or more likely, some UI framework.

同样,为了便于演示,代码片段在窗口对象上使用了命名访问,但在生产中,您应该使用标准化的api,比如getElementById,或者更可能是一些UI框架。

#2


175  

As of this writing, only one of the other answers correctly handles DST (daylight saving time) transitions. Here are the results on a system located in California:

在撰写本文时,其他答案中只有一个正确地处理了DST(夏令时)转换。以下是加利福尼亚的一个系统的结果:

                                        1/1/2013- 3/10/2013- 11/3/2013-
User       Formula                      2/1/2013  3/11/2013  11/4/2013  Result
---------  ---------------------------  --------  ---------  ---------  ---------
Miles                   (d2 - d1) / N   31        0.9583333  1.0416666  Incorrect
some         Math.floor((d2 - d1) / N)  31        0          1          Incorrect
fuentesjr    Math.round((d2 - d1) / N)  31        1          1          Correct
toloco     Math.ceiling((d2 - d1) / N)  31        1          2          Incorrect

N = 86400000

Although Math.round returns the correct results, I think it's somewhat clunky. Instead, by explicitly accounting for changes to the UTC offset when DST begins or ends, we can use exact arithmetic:

虽然数学。round返回的结果是正确的,我认为有点笨拙。相反,通过显式地计算当DST开始或结束时UTC偏移量的变化,我们可以使用精确的算术:

function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

function daysBetween(startDate, endDate) {
    var millisecondsPerDay = 24 * 60 * 60 * 1000;
    return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}

alert(daysBetween($('#first').val(), $('#second').val()));

Explanation

JavaScript date calculations are tricky because Date objects store times internally in UTC, not local time. For example, 3/10/2013 12:00 AM Pacific Standard Time (UTC-08:00) is stored as 3/10/2013 8:00 AM UTC, and 3/11/2013 12:00 AM Pacific Daylight Time (UTC-07:00) is stored as 3/11/2013 7:00 AM UTC. On this day, midnight to midnight local time is only 23 hours in UTC!

JavaScript日期计算很棘手,因为日期对象在UTC内部存储时间,而不是本地时间。例如,3/10/2013太平洋标准时间(UTC-08:00)存储为3/10/2013上午8:00;3/11/2013太平洋夏令时(UTC-07:00)存储为3/11/2013上午7:00。在这一天,从午夜到午夜当地时间在UTC只有23小时!

Although a day in local time can have more or less than 24 hours, a day in UTC is always exactly 24 hours.1 The daysBetween method shown above takes advantage of this fact by first calling treatAsUTC to adjust both local times to midnight UTC, before subtracting and dividing.

虽然在当地时间的一天可以有超过或少于24小时,但在UTC的一天总是完全24小时。上面所示的daysBetween方法利用了这一事实,首先调用treatAsUTC来调整两个本地时间到UTC午夜,然后减去和分割。

1. JavaScript ignores leap seconds.

1。JavaScript忽略了闰秒。

#3


102  

The easiest way to get the difference between two dates:

最简单的方法来区分两个日期:

var diff =  Math.floor(( Date.parse(str2) - Date.parse(str1) ) / 86400000); 

You get the difference days (or NaN if one or both could not be parsed). The parse date gived the result in milliseconds and to get it by day you have to divided it by 24 * 60 * 60 * 1000

您将获得差异日(或NaN,如果一个或两个都不能被解析)。解析日期以毫秒为单位给出结果,要在一天之内得到结果,必须将其除以24 * 60 * 60 * 1000

If you want it divided by days, hours, minutes, seconds and milliseconds:

如果你想要它除以天、小时、分钟、秒和毫秒:

function dateDiff( str1, str2 ) {
    var diff = Date.parse( str2 ) - Date.parse( str1 ); 
    return isNaN( diff ) ? NaN : {
        diff : diff,
        ms : Math.floor( diff            % 1000 ),
        s  : Math.floor( diff /     1000 %   60 ),
        m  : Math.floor( diff /    60000 %   60 ),
        h  : Math.floor( diff /  3600000 %   24 ),
        d  : Math.floor( diff / 86400000        )
    };
}

Here is my refactored version of James version:

以下是我重构的詹姆斯版本:

function mydiff(date1,date2,interval) {
    var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
    date1 = new Date(date1);
    date2 = new Date(date2);
    var timediff = date2 - date1;
    if (isNaN(timediff)) return NaN;
    switch (interval) {
        case "years": return date2.getFullYear() - date1.getFullYear();
        case "months": return (
            ( date2.getFullYear() * 12 + date2.getMonth() )
            -
            ( date1.getFullYear() * 12 + date1.getMonth() )
        );
        case "weeks"  : return Math.floor(timediff / week);
        case "days"   : return Math.floor(timediff / day); 
        case "hours"  : return Math.floor(timediff / hour); 
        case "minutes": return Math.floor(timediff / minute);
        case "seconds": return Math.floor(timediff / second);
        default: return undefined;
    }
}

#4


70  

I recommend using the moment.js library (http://momentjs.com/docs/#/displaying/difference/). It handles daylight savings time correctly and in general is great to work with.

我推荐使用这个时刻。js库(http://momentjs.com/docs/ /显示/ /)差异。它正确地处理日光节约时间,而且一般来说,它很好用。

Example:

例子:

var start = moment("2013-11-03");
var end = moment("2013-11-04");
end.diff(start, "days")
1

#5


39  

I would go ahead and grab this small utility and in it you will find functions to this for you. Here's a short example:

我来获取这个小工具,在它里面你可以找到它的函数。这是一个简短的例子:

        <script type="text/javascript" src="date.js"></script>
        <script type="text/javascript">
            var minutes = 1000*60;
            var hours = minutes*60;
            var days = hours*24;

            var foo_date1 = getDateFromFormat("02/10/2009", "M/d/y");
            var foo_date2 = getDateFromFormat("02/12/2009", "M/d/y");

            var diff_date = Math.round((foo_date2 - foo_date1)/days);
            alert("Diff date is: " + diff_date );
        </script>

#6


13  

Using Moment.js

使用Moment.js

var future = moment('05/02/2015');
var start = moment('04/23/2015');
var d = future.diff(start, 'days'); // 9
console.log(d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>

#7


8  

Date values in JS are datetime values.

JS中的日期值是datetime值。

So, direct date computations are inconsistent:

因此,直接日期计算是不一致的:

(2013-11-05 00:00:00) - (2013-11-04 10:10:10) < 1 day

for example we need to convert de 2nd date:

例如,我们需要转换到第二个日期:

(2013-11-05 00:00:00) - (2013-11-04 00:00:00) = 1 day

the method could be truncate the mills in both dates:

该方法可以在两个日期截断铣刀:

var date1 = new Date('2013/11/04 00:00:00');
var date2 = new Date('2013/11/04 10:10:10'); //less than 1
var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates
console.log(daysDiff);

date2 = new Date('2013/11/05 00:00:00'); //1

var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates
console.log(daysDiff);

#8


7  

To Calculate days between 2 given dates you can use the following code.Dates I use here are Jan 01 2016 and Dec 31 2016

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

var day_start = new Date("Jan 01 2016");
var day_end = new Date("Dec 31 2016");
var total_days = (day_end - day_start) / (1000 * 60 * 60 * 24);
document.getElementById("demo").innerHTML = Math.round(total_days);
<h3>DAYS BETWEEN GIVEN DATES</h3>
<p id="demo"></p>

#9


6  

What about using formatDate from DatePicker widget? You could use it to convert the dates in timestamp format (milliseconds since 01/01/1970) and then do a simple subtraction.

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

#10


6  

I found this question when I want do some calculate on two date, but the date have hours and minutes value, I modified @michael-liu 's answer to fit my requirement, and it passed my test.

当我想计算两个日期时,我发现了这个问题,但是这个日期有小时和分钟的值,我修改了@michael-liu的答案以符合我的要求,它通过了我的测试。

diff days 2012-12-31 23:00 and 2013-01-01 01:00 should equal 1. (2 hour) diff days 2012-12-31 01:00 and 2013-01-01 23:00 should equal 1. (46 hour)

2012-12-31 23:00和2013-01-01 01:00应该等于1。(2小时)2012-12-31 01:00和2013-01-01 23:00应该等于1。(46个小时)

function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

var millisecondsPerDay = 24 * 60 * 60 * 1000;
function diffDays(startDate, endDate) {
    return Math.floor(treatAsUTC(endDate) / millisecondsPerDay) - Math.floor(treatAsUTC(startDate) / millisecondsPerDay);
}

#11


6  

I think the solutions aren't correct 100% I would use ceil instead of floor, round will work but it isn't the right operation.

我认为解决方案并不是100%的正确,我将使用ceil而不是floor, round会起作用,但它不是正确的操作。

function dateDiff(str1, str2){
    var diff = Date.parse(str2) - Date.parse(str1); 
    return isNaN(diff) ? NaN : {
        diff: diff,
        ms: Math.ceil(diff % 1000),
        s: Math.ceil(diff / 1000 % 60),
        m: Math.ceil(diff / 60000 % 60),
        h: Math.ceil(diff / 3600000 % 24),
        d: Math.ceil(diff / 86400000)
    };
}

#12


6  

It is possible to calculate a full proof days difference between two dates resting across different TZs using the following formula:

使用以下公式,可以计算出不同TZs上的两个日期之间的完整证明日差异:

var start = new Date('10/3/2015');
var end = new Date('11/2/2015');
var days = (end - start) / 1000 / 60 / 60 / 24;
console.log(days);
// actually its 30 ; but due to daylight savings will show 31.0xxx
// which you need to offset as below
days = days - (end.getTimezoneOffset() - start.getTimezoneOffset()) / (60 * 24);
console.log(days);

#13


5  

Better to get rid of DST, Math.ceil, Math.floor etc. by using UTC times:

最好摆脱DST,数学。装天花板,数学。使用UTC时间:

var firstDate = Date.UTC(2015,01,2);
var secondDate = Date.UTC(2015,04,22);
var diff = Math.abs((firstDate.valueOf() 
    - secondDate.valueOf())/(24*60*60*1000));

This example gives difference 109 days. 24*60*60*1000 is one day in milliseconds.

这个例子给出了109天的差值。24*60*60*1000是一天的毫秒数。

#14


5  

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

jsfiddle example :)

jsfiddle例子:)

#15


4  

Be careful when using milliseconds.

使用毫秒时要小心。

The date.getTime() returns milliseconds and doing math operation with milliseconds requires to include

gettime()返回毫秒,需要使用毫秒执行数学操作

  • Daylight Saving Time (DST)
  • 夏令时(DST)
  • checking if both dates have the same time (hours, minutes, seconds, milliseconds)
  • 检查两个日期是否有相同的时间(小时、分钟、秒、毫秒)
  • make sure what behavior of days diff is required: 19 September 2016 - 29 September 2016 = 1 or 2 days difference?
  • 确定需要的天数差异行为:2016年9月19日- 2016年9月29日= 1天或2天的差异?

The example from comment above is the best solution I found so far https://*.com/a/11252167/2091095 . But use +1 to its result if you want the to count all days involved.

上面注释中的示例是我到目前为止找到的最佳解决方案:https://*.com/a/11252167/2091095。但是如果您想要计算所有涉及的天数的话,可以使用+1作为结果。

function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

function daysBetween(startDate, endDate) {
    var millisecondsPerDay = 24 * 60 * 60 * 1000;
    return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}

var diff = daysBetween($('#first').val(), $('#second').val()) + 1;

#16


4  

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()));

#17


4  

Date.prototype.days = function(to) {
  return Math.abs(Math.floor(to.getTime() / (3600 * 24 * 1000)) - Math.floor(this.getTime() / (3600 * 24 * 1000)))
}


console.log(new Date('2014/05/20').days(new Date('2014/05/23'))); // 3 days

console.log(new Date('2014/05/23').days(new Date('2014/05/20'))); // 3 days

#18


3  

This may not be the most elegant solution, but it seems to answer the question with a relatively simple bit of code, I think. Can't you use something like this:

这可能不是最优雅的解决方案,但我认为它似乎用相对简单的代码来回答这个问题。你不能用这样的东西:

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

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

return dayCount; 
}

This is assuming you are passing date objects as parameters.

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

#19


3  

I had the same issue in Angular. I do the copy because else he will overwrite the first date. Both dates must have time 00:00:00 (obviously)

我在角度上也有同样的问题。我做这个拷贝,因为他会重写第一次约会。两个日期必须都有时间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;
};

#20


3  

If you have two unix timestamps, you can use this function (made a little more verbose for the sake of clarity):

如果您有两个unix时间戳,您可以使用这个函数(为了清晰起见,可以更详细地说明):

// Calculate number of days between two unix timestamps
// ------------------------------------------------------------
var daysBetween = function(timeStampA, timeStampB) {
    var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
    var firstDate = new Date(timeStampA * 1000);
    var secondDate = new Date(timeStampB * 1000);
    var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
    return diffDays;
};

Example:

例子:

daysBetween(1096580303, 1308713220); // 2455

#21


3  

I used below code to experiment the posting date functionality for a news post.I calculate the minute or hour or day or year based on the posting date and current date.

我用下面的代码来测试一个新闻帖子的发布日期功能。我根据投寄日期及现时日期计算每一分钟或一小时或一天或一年。

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");
}

#22


3  

if you wanna have an DateArray with dates try this:

如果你想要一个带有日期的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>

DebugSnippet

DebugSnippet

#23


2  

function formatDate(seconds, dictionary) {
    var foo = new Date;
    var unixtime_ms = foo.getTime();
    var unixtime = parseInt(unixtime_ms / 1000);
    var diff = unixtime - seconds;
    var display_date;
    if (diff <= 0) {
        display_date = dictionary.now;
    } else if (diff < 60) {
        if (diff == 1) {
            display_date = diff + ' ' + dictionary.second;
        } else {
            display_date = diff + ' ' + dictionary.seconds;
        }
    } else if (diff < 3540) {
        diff = Math.round(diff / 60);
        if (diff == 1) {
            display_date = diff + ' ' + dictionary.minute;
        } else {
            display_date = diff + ' ' + dictionary.minutes;
        }
    } else if (diff < 82800) {
        diff = Math.round(diff / 3600);
        if (diff == 1) {
            display_date = diff + ' ' + dictionary.hour;
        } else {
            display_date = diff + ' ' + dictionary.hours;
        }
    } else {
        diff = Math.round(diff / 86400);
        if (diff == 1) {
            display_date = diff + ' ' + dictionary.day;
        } else {
            display_date = diff + ' ' + dictionary.days;
        }
    }
    return display_date;
}

#24


2  

const startDate = '2017-11-08';
const endDate   = '2017-10-01';
const timeDiff  = (new Date(startDate)) - (new Date(endDate));
const days      = timeDiff / (1000 * 60 * 60 * 24)
  1. Set start date
  2. 设置开始日期
  3. Set end date
  4. 设置结束日期
  5. Calculate difference
  6. 计算的区别
  7. Convert milliseconds to days
  8. 毫秒为单位转换为天

#25


1  

If you want a solution that works like the moment.js answers without the library overhead, you can use this component I wrote.

如果你想要一个像现在这样的解决方案。js回答不需要占用库开销,您可以使用我编写的这个组件。

For getting days:

让天:

var date1 = new Date('January 24, 1984 09:41:00');
var date2 = new Date('June 29, 2007 18:45:10');

var numDays = dateDiff(date1, date2, 'days');

In addition to calculating the number of days between two dates it can also calculate all the other standard time units (seconds, hours, weeks, months, etc.).

除了计算两个日期之间的天数之外,它还可以计算所有其他的标准时间单位(秒、小时、周、月等)。

To use the dateDiff() method you can import the component.

要使用dateDiff()方法,可以导入组件。

#26


1  

The simple way to calculate days between two dates is to remove both of their time component i.e. setting hours, minutes, seconds and milliseconds to 0 and then subtracting their time and diving it with milliseconds worth of one day.

计算两个日期之间的天数的简单方法是去掉它们的时间成分,即将小时、分钟、秒和毫秒设置为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);

#27


1  

A Better Solution by

一个更好的解决方案,

Ignoring time part

忽略时间的一部分

it will return 0 if both the dates are same.

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

#28


0  

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

#29


0  

You can use UnderscoreJS for formatting and calculating difference.

您可以使用UnderscoreJS进行格式化和计算差异。

Demo https://jsfiddle.net/sumitridhal/8sv94msp/

演示https://jsfiddle.net/sumitridhal/8sv94msp/

 var startDate = moment("2016-08-29T23:35:01");
var endDate = moment("2016-08-30T23:35:01");  
  

console.log(startDate);
console.log(endDate);

var resultHours = endDate.diff(startDate, 'hours', true);

document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(resultHours));
body { white-space: pre; font-family: monospace; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>

#30


0  

Bookmarklet version of other answers, prompting you for both dates:

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)
             )
        ));
})();