By chobo2


2010-07-11 22:19:54 8 Comments

How do I get the difference between 2 dates in full days (I don't want any fractions of a day)

var date1 = new Date('7/11/2010');
var date2 = new Date('12/12/2010');
var diffDays = date2.getDate() - date1.getDate(); 
alert(diffDays)

I tried the above but this did not work.

6 comments

@TNi 2010-07-11 22:24:46

Here is one way:

const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
console.log(diffDays);

Observe that we need to enclose the date in quotes. The rest of the code gets the time difference in milliseconds and then divides to get the number of days. Date expects mm/dd/yyyy format.

@chobo2 2010-07-11 22:27:57

Ah the quotes was a typo. Still I get like 1 day with my way.

@chobo2 2010-07-11 22:28:41

Whats (1000 * 3600 * 24) what is each of those (mins?seconds? hours?)

@chobo2 2010-07-11 22:33:11

Another problem that what yours has and @volkan er does not seem to have is if date2 is less than date 1 yours will give a positive number instead of negative.

@TNi 2010-07-11 22:38:30

As volkan answered below, the 1000 * 3600 * 24 is the number of milliseconds per day. As for always returning a positive number, that was a feature :) Typically when one talks about the number of days between two dates, that number is positive. If direction matters, just remove the Math.abs().

@TNi 2010-07-11 22:40:14

Likewise, you get 1 day with your method, because getDate() returns the day without regards to the month. Thus, you would get 12 - 11 = 1.

@volkan er 2010-07-11 22:56:53

date already returned time do not need to call .getTime()

@TNi 2010-07-11 23:08:31

@volkan er: Indeed, you're right. I can't ever remember things like that.

@Zemljoradnik 2013-06-24 10:31:50

For this to work correctly with daylight saving, Math.round should replace Math.ceil. But I think Shyam's answer is the way to go.

@Dalius 2013-11-29 12:05:23

@Zemljoradnik , would you mind explaining why it won't work? getTime() returns UTC timestamps, so why is this not going to work?

@Shyam Habarakada 2014-03-04 15:39:50

@Dalius the above doesn't work because the Date constructor creates the date in the local time zone. So, the UTC timestamps you get via getTime(), while being UTC values, reflect the DST adjusted value of the date. IOW, garbage in garbage out :-)

@RobG 2014-04-28 12:09:44

This is a very poor answer as parsing of date strings should never be left to the Date constructor. For most people in the world, 7/11/2010 represents 7 November, but most browsers treat it as 11 July.

@Alaeddine 2014-06-24 03:44:02

between 7/11/2010 and 12/12/2010 155 day ??

@gmail user 2014-09-02 19:45:42

I think it should be Math.floor instead of Math.ceil. Because Math.floor(120.12323) will return 120. And Math.ceil(120.1232144) will return 121.

@Jim 2015-03-08 03:13:01

Won't work with a 23 hour 25 hour day in the calculated span. It would be helpful to consult a detailed treatment of UTC (Universal Coordinated Time) and "civil" time standards before devising a calculation such as this. A day is not a always 86,400 seconds, not even in UTC. However, ECMA standards state that it will not have the 58, 59, 61, or 62 second minutes that occur up to twice a year in UTC. You must not assume that offsets from epoch (00:00:00 hours 1 January 1970) in other languages and operating systems will be the same since some of them have 58, 59, 61, and 62 second minutes.

@Ninja Coding 2017-07-07 16:38:44

Warning! this "solution" always gives positive numbers, wich is wrong when you want the difference between a past Date and current Date by example.

@nonzaprej 2017-11-15 10:50:54

I tried this with 03/11/2017 - 29/10/2017 and I got 6 days. Math.ceil isn't the right solution for all cases. I upvoted this answer prematurely.

@Sérgio S. Filho 2018-03-02 03:34:24

the result can be unexpected if the two days are not in the same GMT (I got an error when the timezone changed for some periods of the year)

@volkan er 2010-07-11 22:27:31

var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 

alert(diffDays )

@chobo2 2010-07-11 22:32:23

What is 1000 * 60 * 60 * 24?

@volkan er 2010-07-11 22:36:25

date2 - date1 => milliseconds output (1000 * 60 * 60 * 24) => milisecond to day

@Christian 2010-07-11 23:02:57

Isn't parseInt completely unnecessary?

@volkan er 2010-07-11 23:06:16

to get full value in terms of number of days; request and will be subject to work-related...

@Dagg Nabbit 2010-07-12 00:05:00

Christian: he wanted an integral number. parseInt is probably the worst way to do it. Math.round is the 'normal' way; it rounds instead of truncating. If truncating was desired, 'or'ing the expression with 0 would suffice: (date2 - date1) / (1000 * 60 * 60 * 24) | 0

@ontananza 2015-03-24 22:54:14

Note that this solution isnt completely accurate as, in some cases i.e. 2015-04-06 minus 2015-04-04 gives an erroneous 1 day, all about parseInt() aproach.

@Garr Godfrey 2018-02-02 08:37:31

because some days are only 23 hours long.

@I am ok 2019-01-18 20:18:52

@ontananza var date1 = new Date("2015-04-04"); var date2 = new Date("2015-04-06"); parseInt((date2 - date1) / (1000 * 60 * 60 * 24)); yields 2 for me

@I am ok 2019-01-18 20:19:55

@GarrGodfrey What planet do you live on?

@Garr Godfrey 2019-01-22 00:03:25

In areas that have daylight savings time, there is one day each year that is actually only 23 hours long.

@Shyam Habarakada 2013-03-08 08:43:25

A more correct solution

... since dates naturally have time-zone information, which can span regions with different day light savings adjustments

Previous answers to this question don't account for cases where the two dates in question span a daylight saving time (DST) change. The date on which the DST change happens will have a duration in milliseconds which is != 1000*60*60*24, so the typical calculation will fail.

You can work around this by first normalizing the two dates to UTC, and then calculating the difference between those two UTC dates.

Now, the solution can be written as,

const _MS_PER_DAY = 1000 * 60 * 60 * 24;

// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// test it
const a = new Date("2017-01-01"),
    b = new Date("2017-07-25"),
    difference = dateDiffInDays(a, b);

This works because UTC time never observes DST. See Does UTC observe daylight saving time?

p.s. After discussing some of the comments on this answer, once you've understood the issues with javascript dates that span a DST boundary, there is likely more than just one way to solve it. What I provided above is a simple (and tested) solution. I'd be interested to know if there is a simple arithmetic/math based solution instead of having to instantiate the two new Date objects. That could potentially be faster.

@obenjiro 2013-04-05 08:26:54

this is the ONLY correct answer, i don't understand why other answer if accepted

@Shyam Habarakada 2013-04-06 20:47:05

probably because @chobo2 has not come back and looked at this question

@Scott Sauyet 2013-08-21 00:56:25

@Ai_boy: While this is the most logically correct answer, there are no values for which it will fail to match the simpler Math.round((b - a)/ _MS_PER_DAY, 0), so it's difficult to support "the ONLY correct answer".

@Shyam Habarakada 2013-08-21 01:23:56

@ScottSauyet the issue we ran into was when a and b spanned across the day-light savings switch. When you say 'there are no values', have you included that as a scenario?

@Scott Sauyet 2013-08-21 01:30:26

@ShyamHabarakada: That's a problem with a Math.ceil or Math.floor technique, but since daylight savings only adjusts by one hour from a 24-hour day, it will be swallowed up by Math.round. I haven't tested exhaustively, but I can see no case where the two would disagree. Can you? We're actually discussing this in 18347050, which is how I ran across this old thread, and I brought up Daylight Savings there.

@Shyam Habarakada 2013-09-10 00:49:30

Yes, rounding probably works as you describe, and assuming a and b are values in the same timezone, etc. but it fails in scenarios where a and b are datetime objects that aren't in the same time zone. For instance, try: var a = new Date("Mon Sep 09 2013 17:46:44 GMT+0800 (PDT)"); and b = new Date("Mon Sep 09 2013 17:46:44 GMT-0700 (PDT)"), and then apply the Math.round technique to these dates.

@IcanDivideBy0 2013-10-08 14:06:05

+1 for removing the annoying alert

@Alex G 2014-09-21 05:18:21

How about providing return in hours?

@Shyam Habarakada 2014-09-24 22:09:49

@Radio can you clarify what you mean? Maybe an example...

@RobG 2014-09-29 01:39:24

This answer is wrong. Javascript Date objects are UTC. Using local values to generate a UTC date will ignore daylight saving, so if the difference was supposed to be local then treating the dates as UTC will remove daylight saving (so the answer may be wrong over a daylight saving boundary).

@Shyam Habarakada 2014-10-14 07:27:15

@RobG that's an interesting scenario, but I am not sure if I completely follow. Can you give an example? I use this code in an app, so if there is a bug, I'd really like to fix it :-)

@Mr. Duc Nguyen 2014-12-14 22:41:43

Suppose that Javascript runs on client side, this answer is innecessarily complex. Please read getTime() and UTC(). They both return the miliseconds from midnight January 1, 1970.

@Shyam Habarakada 2015-02-12 02:24:54

@Mr.DucNguyen I am not sure what you are pointing out. In the code, Date.UTC is used to construct a new date object in the UTC time-zone. The getTime() function on an already_initialized object return the milliseconds from UTC. Compare the difference between d1 = new Date(2015,1,1) and d2 = new Date(Date.UTC(2015,1,1)); and you will understand what the code does. Thanks

@Mr. Duc Nguyen 2015-02-22 23:16:39

@ShyamHabarakada I'm not sure why you were giving out the 2 dates in your comment. They are clearly different. Can you point out what is the different between: t1 = (new Date(2015, 2, 1)).getTime() and t2 = Date.UTC(2015, 2, 1) ? We are looking at these numbers to tell the different of 2 date objects. It's not the other way around, isn't it?

@Jim 2015-03-08 03:03:23

Using UTC instead of a local time zone will correct the problems caused by 23 hour and 25 hour days in civil time systems. UTC also has 58, 59, 61, and 62 second minutes up to twice a year, so a day in UTC will not always have 86,400 seconds. However, ECMA standards state that JavaScript does not incorporate these adjustments so ignoring them when working purely in JavaScript works. However, other system do not ignore them and you must not assume offsets from the epoch moment (00:00:00 January 1, 1970) will always be the same between programming languages and operating systems.

@ivkremer 2015-04-24 14:37:04

This is strange but it seems there is no such method in momentJS. There is a diff() method, but it doesn't calculate the actual calendar difference, so e.g. moment('2015-04-24T14:00:00.000Z').diff(moment('2015-04-24T1‌​1:00:00.000Z'), 'days') will result to zero which is obviously not true in terms of whether this is the same date or not.

@Shyam Habarakada 2015-06-16 18:53:04

@Mr.DucNguyen I am not sure I understood your question. The examples you gave have the values (new Date(2015, 2, 1)).getTime() => 1425196800000 and Date.UTC(2015, 2, 1) => 1425168000000. These dates, when converted to the same time-zone, comes out as Sun Mar 01 2015 00:00:00 GMT-0800 (PST) and Sat Feb 28 2015 16:00:00 GMT-0800 (PST) respectively. And the difference between those dates is 1 (or -1 if you reverse the comparison order). Does that make sense?

@Simmant 2015-06-18 11:43:36

great Help. I am agree with @Ai_boy this answer need to accepted. Before I was using the answer which marked as a accepted but I am not getting result which I am looking for. I try accepted answer for date 06/15/2015 and 10/17/2015 the days difference I got is 122 days which is wrong when I try the your code snap result is 124 days and its correct . thanks for such a nice answer +1.

@RobG 2016-02-20 08:21:16

@ShyamHabarakada—"local" date objects consider the system timezone setting when creating a date. The internal value is UTC, so if a place changes to DST at 02:00 and local dates are created for 01:00 and 03:00 for that day, the time difference (i.e. between the time values of the two dates) should be 1 hour, not 2 (since 02:00 instantly becomes 03:00). If you create dates using UTC for 01:00 and 03:00 the time difference will be 2 hours as there is no allowance for DST. But anyway, if the OP is only interested in whole days, rounding will fix DST variance since it's never more than 1 hour.

@Shyam Habarakada 2016-02-25 20:04:28

@RobG that is correct. Depending on what you mean by rounding ... that is what the solution above does in a way. It takes any date and rounds it to a UTC zoned date at 00:00:00 and then does the math to find the difference. OP says they want the difference in full days. Thinking about it more, I don't know if there is any other definition for difference between two dates in days besides it being in full days.

@RobG 2016-02-25 21:01:14

@ShyamHabarakada—the OP didn't indicate any requirement for UTC, only the use of dates without either timezones or times, so using those values to create "local" date objects, subtracting, dividing by ms/day and rounding will produce exactly the same result as using UTC methods. The only difference is that the UTC version doesn't need rounding as it's never affected by DST if it's run on a system that's set to observe it.

@Shyam Habarakada 2016-05-26 09:47:07

@RobG lack of UTC requirements isn't the issue. The bug in the current accepted solution shows up if you are using it in a time zone that has day light savings changes and the dates that are being used as inputs span such DST change. HTH

@RobG 2016-05-26 14:15:59

@ShyamHabarakada—whatever. If only whole days are required, Math.round((a-b)/8.64e7) does the job.

@Edward 2016-09-04 20:53:41

Also see stackoverflow.com/questions/1968167/… for a similar answer with a function to get the maximum whole amount of a time unit in the value of a lower unit and the remainder lower unit for any amount of higher units (e.g. get whole minutes and whole remaining seconds and milliseconds). Note the answer doesn't cover cases where the two dates in question span a daylight saving time (DST) change.

@Shyam Habarakada 2016-12-27 22:06:06

@RobG hello again :-) I haven't followed your thinking to form a complete answer to the question in my head. Feel free to submit an edit or a new answer. Cheers, and happy new year.

@MSwezey 2017-02-28 20:26:05

This solution worked well for my needs in doing JS Rules in AEM 6.2 Adaptive Forms. I needed to return the difference in dates, in # of days, with positive and negative results.

@Nalla Srinivas 2017-10-26 08:55:14

var a = new Date(2017,9,25); var b = new Date(2017,10,6); for these dates i am getting 12 days diff but incase of, var a = new Date(2017,10,25); var b = new Date(2017,11,5); i am getting 11 days. This is wrong. i should get 13 days

@Shyam Habarakada 2018-01-18 16:58:45

@NallaSrinivas I tested your case and looks like the result is correct. Keep in mind when you create those dates, javascript by default creates a date-time object at 00:00:00 hours on the given day. So when you give it "2017-11-05" for instance, it's actually creating a date object that represents midnight the previous day, and when counting differences, it won't count the 05th. If you want to include the 5th, you should be doing +1.

@Brian Smith 2018-02-27 01:38:51

This should be listed as the accepted answer.

@binaryfunt 2018-09-08 17:05:50

Math.trunc() should be used instead of Math.floor() to give correct results for negative numbers (i.e. when utc1 > utc2)

@binaryfunt 2018-09-08 17:14:01

But actually, is Math.floor/trunc needed at all? After discarding the time info, won't you always get an integer number of days returned?

@Miguel Stevens 2019-07-04 16:02:42

Is it possible to get the difference in seconds using this method?

@Shyam Habarakada 2019-07-21 20:37:27

@Notflip depends on your definition of difference in seconds. If you want the number-od-days-difference multiplied by seconds in a day, yes sure you can leverage this method. But again, the answer depends on your exact definition... HTH

@Abhinav 2019-12-07 01:39:02

@ShyamHabarakada In your answer, the date is in Y-m-d format. Is this mandatory ? cos in other answers its in m-d-y format?

@Mikeys4u 2014-05-01 09:19:21

I tried lots of ways, and found that using datepicker was the best, but the date format causes problems with JavaScript....

So here's my answer and can be run out of the box.

<input type="text" id="startdate">
<input type="text" id="enddate">
<input type="text" id="days">

<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script>
$(document).ready(function() {

$( "#startdate,#enddate" ).datepicker({
changeMonth: true,
changeYear: true,
firstDay: 1,
dateFormat: 'dd/mm/yy',
})

$( "#startdate" ).datepicker({ dateFormat: 'dd-mm-yy' });
$( "#enddate" ).datepicker({ dateFormat: 'dd-mm-yy' });

$('#enddate').change(function() {
var start = $('#startdate').datepicker('getDate');
var end   = $('#enddate').datepicker('getDate');

if (start<end) {
var days   = (end - start)/1000/60/60/24;
$('#days').val(days);
}
else {
alert ("You cant come back before you have been!");
$('#startdate').val("");
$('#enddate').val("");
$('#days').val("");
}
}); //end change function
}); //end ready
</script>

a Fiddle can be seen here DEMO

@Alexander 2018-05-12 06:30:19

This is a similar problem to what I have the problem with this solution is that if the user clicks on the date2 datepicker first, then it fails.

@Pec1983 2015-05-12 14:37:45

This is the code to subtract one date from another. This example converts the dates to objects as the getTime() function won't work unless it's an Date object.

    var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);

                var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                var diffDays = Math.abs((date1.getTime() - date2.getTime()) / (oneDay));
                alert(diffDays);

@Matt Johnson-Pint 2013-09-07 17:27:34

Here is a solution using moment.js:

var a = moment('7/11/2010','M/D/YYYY');
var b = moment('12/12/2010','M/D/YYYY');
var diffDays = b.diff(a, 'days');
alert(diffDays);

I used your original input values, but you didn't specify the format so I assumed the first value was July 11th. If it was intended to be November 7th, then adjust the format to D/M/YYYY instead.

@jhhoff02 2016-09-06 12:54:44

Cheers, I was looking for a momentjs solution

@Imdad Ali 2018-05-31 17:59:09

@Matt Johnson: I have req to find the exact difference, I mean, number of days, Hours, Min and seconds remaining to a future date from this time? How to do that?

@Matt Johnson-Pint 2018-05-31 20:37:02

@codemirror 2019-03-01 10:33:13

Just note that moment.js is a big dependency

Related Questions

Sponsored Content

89 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6158015 View
  • 7682 Score
  • 89 Answer
  • Tags:   javascript arrays

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

38 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

54 Answered Questions

[SOLVED] How to format a JavaScript date

58 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

33 Answered Questions

[SOLVED] What's the difference between using "let" and "var"?

3 Answered Questions

49 Answered Questions

[SOLVED] How do I get the current date in JavaScript?

  • 2009-10-07 11:39:02
  • Suresh Chaganti
  • 2510042 View
  • 2170 Score
  • 49 Answer
  • Tags:   javascript date

21 Answered Questions

[SOLVED] What is the difference between call and apply?

Sponsored Content