How to calculate number of days between two dates?

JavascriptDate

Javascript Problem Overview


For example, given two dates in input boxes:

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

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

How do I get the number of days between two dates in JavaScript?

Javascript Solutions


Solution 1 - Javascript

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).

// 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.

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.

Solution 2 - Javascript

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:

                                        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:

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!

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.

1. JavaScript ignores leap seconds.

Solution 3 - Javascript

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

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

Solution 4 - Javascript

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.

Example:

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

Solution 5 - Javascript

Steps

  1. Set start date
  2. Set end date
  3. Calculate difference
  4. Convert milliseconds to days

Native JS

const startDate  = '2020-01-01';
const endDate    = '2020-03-15';

const diffInMs   = new Date(endDate) - new Date(startDate)
const diffInDays = diffInMs / (1000 * 60 * 60 * 24);

Comment

I know this is not part of your questions but in general, I would not recommend doing any date calculation or manipulation in vanilla JavaScript and rather use a library like date-fns, Luxon or moment.js for it due to many edge cases.


Using a library

Date-fns

https://date-fns.org/v2.16.1/docs/differenceInDays

const differenceInDays = require('date-fns/differenceInDays');

const startDate  = '2020-01-01';
const endDate    = '2020-03-15';

const diffInDays = differenceInDays(new Date(endDate), new Date(startDate));
Luxon

https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-diff

const { DateTime } = require('luxon');

const startDate  = '2020-01-01';
const endDate    = '2020-03-15';

const diffInDays = DateTime.fromISO(endDate).diff(DateTime.fromISO(startDate), 'days').toObject().days;
Moment.js

https://momentjs.com/docs/#/displaying/difference/

const moment = require('moment');

const startDate  = '2020-01-01';
const endDate    = '2020-03-15';

const diffInDays = moment(endDate).diff(moment(startDate), 'days');
Examples on RunKit

https://runkit.com/marcobiedermann/5f573e211e85e7001a37ab00

Solution 6 - Javascript

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>

Solution 7 - Javascript

Using 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>

Solution 8 - Javascript

Try This

let today = new Date().toISOString().slice(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  );

Solution 9 - Javascript

Date values in JS are datetime values.

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

Solution 10 - Javascript

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

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>

Solution 11 - Javascript

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

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.

Solution 12 - Javascript

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

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

Solution 13 - Javascript

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.

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)

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

Solution 14 - Javascript

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.

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

Solution 15 - Javascript

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.

Solution 16 - Javascript

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

jsfiddle example :)

Solution 17 - Javascript

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.

Solution 18 - Javascript

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

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

Solution 20 - Javascript

Simple, easy, and sophisticated. This function will be called in every 1 sec to update time.

const year = (new Date().getFullYear());
const bdayDate = new Date("04,11,2019").getTime(); //mmddyyyy

// countdown
let timer = setInterval(function () {

	// get today's date
	const today = new Date().getTime();

	// get the difference
	const diff = bdayDate - today;

	// math
	let days = Math.floor(diff / (1000 * 60 * 60 * 24));
	let hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	let minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
	let seconds = Math.floor((diff % (1000 * 60)) / 1000);

}, 1000);

Solution 21 - Javascript

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)

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

Solution 22 - Javascript

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

// 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

Solution 23 - Javascript

Be careful when using milliseconds.

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

  • Daylight Saving Time (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?

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

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;

Solution 24 - Javascript

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

Solution 25 - Javascript

if you wanna have an DateArray with dates try this:

<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

Solution 26 - Javascript

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.

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

Solution 27 - Javascript

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

Solution 28 - Javascript

I took some inspiration from other answers and made the inputs have automatic sanitation. I hope this works well as an improvement over other answers.

//use best practices by labeling your constants. let MS_PER_SEC = 1000 , SEC_PER_HR = 60 * 60 , HR_PER_DAY = 24 , MS_PER_DAY = MS_PER_SEC * SEC_PER_HR * HR_PER_DAY ;

//let's assume we get Date objects as arguments, otherwise return 0.
function dateDiffInDays(date1, date2) {
    if (!date1 || !date2) {
      return 0;
    }
    return Math.round((date2.getTime() - date1.getTime()) / MS_PER_DAY);
}

// new Date("dateString") is browser-dependent and discouraged, so we'll write
// a simple parse function for U.S. date format. (by @Miles)
function parseDate(str) {
    if (str && str.length > 7 && str.length < 11) {
      let mdy = str.split('/');
      return new Date(mdy[2], mdy[0]-1, mdy[1]);
    }
    return null;
}

function calcInputs() {
  let date1 = document.getElementById("date1")
    , date2 = document.getElementById("date2")
    , resultSpan = document.getElementById("result")
  ;
  if (date1 && date2 && resultSpan) {
    //remove non-date characters
    let date1Val = date1.value.replace(/[^\d\/]/g,'')
      , date2Val = date2.value.replace(/[^\d\/]/g,'')
      , result = dateDiffInDays(parseDate(date1Val), parseDate(date2Val))
    ;
    date1.value = date1Val;
    date2.value = date2Val;
    resultSpan.innerHTML = result + " days";
  }
}
window.onload = function() { calcInputs(); };

//some code examples
console.log(dateDiffInDays(parseDate("1/15/2019"), parseDate("1/30/2019")));
console.log(dateDiffInDays(parseDate("1/15/2019"), parseDate("2/30/2019")));
console.log(dateDiffInDays(parseDate("1/15/2000"), parseDate("1/15/2019")));

Result:

Solution 29 - Javascript

One-Liner and small
const diff=(e,t)=>Math.floor((new Date(e).getTime()-new Date(t).getTime())/1000*60*60*24);

// or

const diff=(e,t)=>Math.floor((new Date(e)-new Date(t))/864e5);

// or

const diff=(a,b)=>(new Date(a)-new Date(b))/864e5|0; 

// use
diff('1/1/2001', '1/1/2000')
For TypeScript
const diff=(e,t)=>Math.floor((new Date(e).getTime()-new Date(t).getTime())/86400000);

Solution 30 - Javascript

I recently had the same question, and coming from a Java world, I immediately started to search for a JSR 310 implementation for JavaScript. JSR 310 is a Date and Time API for Java (standard shipped as of Java 8). I think the API is very well designed.

Fortunately, there is a direct port to Javascript, called js-joda.

First, include js-joda in the <head>:

<script
    src="https://cdnjs.cloudflare.com/ajax/libs/js-joda/1.11.0/js-joda.min.js"
    integrity="sha512-piLlO+P2f15QHjUv0DEXBd4HvkL03Orhi30Ur5n1E4Gk2LE4BxiBAP/AD+dxhxpW66DiMY2wZqQWHAuS53RFDg=="
    crossorigin="anonymous"></script>

Then simply do this:

let date1 = JSJoda.LocalDate.of(2020, 12, 1);
let date2 = JSJoda.LocalDate.of(2021, 1, 1);
let daysBetween = JSJoda.ChronoUnit.DAYS.between(date1, date2);

Now daysBetween contains the number of days between. Note that the end date is exclusive.

Solution 31 - Javascript

A Better Solution by

> Ignoring time part

it will return 0 if both the dates are same.

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">

Solution 32 - Javascript

A contribution, for date before 1970-01-01 and after 2038-01-19

function DateDiff(aDate1, aDate2) {
  let dDay = 0;
  this.isBissexto = (aYear) => {
    return (aYear % 4 == 0 && aYear % 100 != 0) || (aYear % 400 == 0);
  };
  this.getDayOfYear = (aDate) => {
    let count = 0;
    for (let m = 0; m < aDate.getUTCMonth(); m++) {
      count += m == 1 ? this.isBissexto(aDate.getUTCFullYear()) ? 29 : 28 : /(3|5|8|10)/.test(m) ? 30 : 31;
    }
    count += aDate.getUTCDate();
    return count;
  };
  this.toDays = () => {
    return dDay;
  };
  (() => {
    let startDate = aDate1.getTime() <= aDate2.getTime() ? new Date(aDate1.toISOString()) : new Date(aDate2.toISOString());
    let endDate = aDate1.getTime() <= aDate2.getTime() ? new Date(aDate2.toISOString()) : new Date(aDate1.toISOString());
    while (startDate.getUTCFullYear() != endDate.getUTCFullYear()) {
      dDay += (this.isBissexto(startDate.getFullYear())? 366 : 365) - this.getDayOfYear(startDate) + 1;
      startDate = new Date(startDate.getUTCFullYear()+1, 0, 1);
    }
    dDay += this.getDayOfYear(endDate) - this.getDayOfYear(startDate);
  })();
}

Solution 33 - Javascript

Using moment will be much easier in this case, You could try this:

    let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days');

It will give you integer value like 1,2,5,0etc so you can easily use condition check like:

if(days < 1) {

Also, one more thing is you can get more accurate result of the time difference (in decimals like 1.2,1.5,0.7etc) to get this kind of result use this syntax:

let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days', true);

Let me know if you have any further query

Solution 34 - Javascript

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

Solution 35 - Javascript

You can use UnderscoreJS for formatting and calculating difference.

Demo 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>

Solution 36 - Javascript

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

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

Solution 37 - Javascript

This answer, based on another one (link at end), is about the difference between two dates.
You can see how it works because it's simple, also it includes splitting the difference into
units of time (a function that I made) and converting to UTC to stop time zone problems.

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

How my code above works

A date/time difference, as milliseconds, can be calculated using the Date object:

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.

Then to work out the number of seconds in that difference, divide it by 1000 to convert
milliseconds to seconds, then change the result to an integer (whole number) to remove
the milliseconds (fraction part of that decimal): var seconds = parseInt(diff/1000).
Also, I could get longer units of time using the same process, for example:
- (whole) minutes, dividing seconds by 60 and changing the result to an integer,
- hours, dividing minutes by 60 and changing the result to an integer.

I created a function for doing that process of splitting the difference into
whole units of time, named split_to_whole_units, with this demo:

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

This answer is based on this other one.

Solution 38 - Javascript

I only got two timestamps in millisecond, so I have to do some extra steps with moment.js to get the days between.

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 

Solution 39 - Javascript

This is bit different answer if we want to calculate our age

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

Solution 40 - Javascript

I had same issue, but it's better if you done it on SQL Query :

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

the query will automatically generate a column CountDays

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael HarenView Question on Stackoverflow
Solution 1 - JavascriptMilesView Answer on Stackoverflow
Solution 2 - JavascriptMichael LiuView Answer on Stackoverflow
Solution 3 - JavascriptsomeView Answer on Stackoverflow
Solution 4 - JavascriptstephenbezView Answer on Stackoverflow
Solution 5 - JavascriptmarcobiedermannView Answer on Stackoverflow
Solution 6 - JavascriptfuentesjrView Answer on Stackoverflow
Solution 7 - JavascriptMichael KView Answer on Stackoverflow
Solution 8 - Javascriptborma425View Answer on Stackoverflow
Solution 9 - JavascriptNorrisView Answer on Stackoverflow
Solution 10 - JavascriptNooNa MarJaView Answer on Stackoverflow
Solution 11 - JavascriptTimo KähkönenView Answer on Stackoverflow
Solution 12 - JavascriptrivView Answer on Stackoverflow
Solution 13 - Javascriptguilin 桂林View Answer on Stackoverflow
Solution 14 - JavascriptTolo PalmerView Answer on Stackoverflow
Solution 15 - JavascriptPopmaticView Answer on Stackoverflow
Solution 16 - JavascriptAravindh GopiView Answer on Stackoverflow
Solution 17 - JavascriptkgiannakakisView Answer on Stackoverflow
Solution 18 - JavascriptAbdennour TOUMIView Answer on Stackoverflow
Solution 19 - JavascriptNoreddine Belhadj CheikhView Answer on Stackoverflow
Solution 20 - JavascriptOhhhThatVarunView Answer on Stackoverflow
Solution 21 - Javascriptuser3806549View Answer on Stackoverflow
Solution 22 - JavascriptWallace SidhréeView Answer on Stackoverflow
Solution 23 - JavascriptDalibor MaturaView Answer on Stackoverflow
Solution 24 - JavascriptRamees RahathView Answer on Stackoverflow
Solution 25 - JavascriptRicardo FercherView Answer on Stackoverflow
Solution 26 - JavascriptSriman PathyView Answer on Stackoverflow
Solution 27 - JavascriptzloctbView Answer on Stackoverflow
Solution 28 - JavascriptlewdevView Answer on Stackoverflow
Solution 29 - JavascriptnkitkuView Answer on Stackoverflow
Solution 30 - JavascriptMC EmperorView Answer on Stackoverflow
Solution 31 - JavascriptSumit JoshiView Answer on Stackoverflow
Solution 32 - JavascriptAdelson Silva CoutoView Answer on Stackoverflow
Solution 33 - JavascriptUmang LoriyaView Answer on Stackoverflow
Solution 34 - JavascriptParmanand SheteView Answer on Stackoverflow
Solution 35 - JavascriptSumit RidhalView Answer on Stackoverflow
Solution 36 - JavascriptdrzausView Answer on Stackoverflow
Solution 37 - JavascriptEdwardView Answer on Stackoverflow
Solution 38 - Javascriptwj2061View Answer on Stackoverflow
Solution 39 - JavascriptMamunur RashidView Answer on Stackoverflow
Solution 40 - JavascriptAlhwaiji Abdulaziz NView Answer on Stackoverflow