Steps:
const diffInMs = new Date(endDate) - new Date(startDate)const diffInDays = diffInMs / (1000 * 60 * 60 * 24);
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.
This vanilla JavaScript answer calculates the days as a decimal number. Also, it could run into edge cases when working with Daylight Savings Time
const differenceInDays = require('date-fns/differenceInDays');const diffInDays = differenceInDays(new Date(endDate), new Date(startDate));
documentation: https://date-fns.org/v2.16.1/docs/differenceInDays
const { DateTime } = require('luxon');const diffInDays = DateTime.fromISO(endDate).diff(DateTime.fromISO(startDate), 'days').toObject().days;
documentation: https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-diff
const moment = require('moment');const diffInDays = moment(endDate).diff(moment(startDate), 'days');
documentation: https://momentjs.com/docs/#/displaying/difference/
Examples on RunKit
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>
Using Moment.js
var future = moment('05/02/2015');var start = moment('04/23/2015');var d = future.diff(start, 'days'); // 9console.log(d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>
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>
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 );
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 1var 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 datesconsole.log(daysDiff);date2 = new Date('2013/11/05 00:00:00'); //1var 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 datesconsole.log(daysDiff);
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.
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 belowdays = days - (end.getTimezoneOffset() - start.getTimezoneOffset()) / (60 * 24);console.log(days);
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);}
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.
var start= $("#firstDate").datepicker("getDate");var end= $("#SecondDate").datepicker("getDate");var days = (end- start) / (1000 * 60 * 60 * 24);alert(Math.round(days));
jsfiddle example :)
const diff=(e,t)=>Math.floor((new Date(e).getTime()-new Date(t).getTime())/1000*60*60*24);// orconst diff=(e,t)=>Math.floor((new Date(e)-new Date(t))/864e5);// orconst diff=(a,b)=>(new Date(a)-new Date(b))/864e5|0; // usediff('1/1/2001', '1/1/2000')
const diff = (from: string, to: string) => Math.floor((new Date(from).getTime() - new Date(to).getTime()) / 86400000);
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)};}
function timeDifference(date1, date2) {var oneDay = 24 * 60 * 60; // hours*minutes*secondsvar oneHour = 60 * 60; // minutes*secondsvar oneMinute = 60; // 60 secondsvar firstDate = date1.getTime(); // convert to millisecondsvar secondDate = date2.getTime(); // convert to millisecondsvar seconds = Math.round(Math.abs(firstDate - secondDate) / 1000); //calculate the diffrence in seconds// the difference objectvar difference = {"days": 0,"hours": 0,"minutes": 0,"seconds": 0,}//calculate all the days and substract it from the totalwhile (seconds >= oneDay) {difference.days++;seconds -= oneDay;}//calculate all the remaining hours then substract it from the totalwhile (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 objectreturn difference;}console.log(timeDifference(new Date(2017,0,1,0,0,0),new Date()));
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.
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;};
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 * millisecondsvar 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
Be careful when using milliseconds.
The date.getTime() returns milliseconds and doing math operation with milliseconds requires to include
The example from comment above is the best solution I found so farhttps://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;
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 daysconsole.log(new Date('2014/05/23').days(new Date('2014/05/20'))); // 3 days
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);
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");}
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
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// countdownlet timer = setInterval(function () {// get today's dateconst today = new Date().getTime();// get the differenceconst diff = bdayDate - today;// mathlet 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);
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;}
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 partsecondDate.setHours(0, 0, 0, 0); //ignore time partvar dayDiff = secondDate - firstDate;dayDiff = dayDiff / 86400000; // divide by milisec in one dayconsole.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">
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>
:
<scriptsrc="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.