How do I get the number of days between two dates in JavaScript? For example, given two dates in input boxes:
Michael Haren
Michael HarenNBC fall TV 2019 schedule: ‘Bluff City Law’ gets ‘Voice’ lead-in, ‘Manifest’ moves to midseason ABC fall TV 2019 schedule: ‘The Rookie’ moves to Sundays, ‘Bless This. Streetwear is bold and stylish retro inspired script typeface suitable for logo, poster, branding, packaging and t-shirt design. It looks like 1960s and 70s fashion and sport related typeface, unique and fun at the same time.
Michael Haren77.5k3838 gold badges149149 silver badges198198 bronze badges
35 Answers
12 next
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). 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
MilesMileswindow
object for brevity, but in production you should use standardized APIs like getElementById, or more likely, some UI framework.25.1k77 gold badges5353 silver badges7070 bronze badges
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:
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: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.
Michael LiuMichael Liu37.6k99 gold badges8686 silver badges124124 bronze badges
The easiest way to get the difference between two dates:
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:
Here is my refactored version of James version:
somesome36.9k1111 gold badges6464 silver badges7979 bronze badges
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:
stephenbezstephenbez4,36522 gold badges1818 silver badges2727 bronze badges
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:
fuentesjrfuentesjr![Baixar fonte worthe numbers Baixar fonte worthe numbers](/uploads/1/2/4/9/124923844/269192330.jpg)
21.3k2626 gold badges6969 silver badges7878 bronze badges
- Set start date
- Set end date
- Calculate difference
- Convert milliseconds to days
marcobiedermannmarcobiedermann
Using Moment.js
Ruslan López3,09411 gold badge1616 silver badges2828 bronze badges
Michael KMichael K
Date values in JS are datetime values.
So, direct date computations are inconsistent:
for example we need to convert de 2nd date:
the method could be truncate the mills in both dates:
Ruslan López3,09411 gold badge1616 silver badges2828 bronze badges
NorrisNorris
Better to get rid of DST, Math.ceil, Math.floor etc. by using UTC times:
This example gives difference 109 days.
Timo KähkönenTimo Kähkönen24*60*60*1000
is one day in milliseconds.8,03066 gold badges5252 silver badges9696 bronze badges
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
mplungjan92.6k2222 gold badges132132 silver badges190190 bronze badges
NooNa MarJaNooNa MarJa
It is possible to calculate a full proof days difference between two dates resting across different TZs using the following formula:
mplungjan92.6k2222 gold badges132132 silver badges190190 bronze badges
rivriv
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
guilin 桂林guilin 桂林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)7,1302323 gold badges8181 silver badges132132 bronze badges
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.
Tolo PalmerTolo Palmer1,43411 gold badge1616 silver badges2525 bronze badges
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.
kgiannakakiskgiannakakis89.3k2323 gold badges147147 silver badges186186 bronze badges
Aravindh GopiAravindh Gopi
mplungjan92.6k2222 gold badges132132 silver badges190190 bronze badges
Noreddine Belhadj CheikhNoreddine Belhadj Cheikh
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:
This is assuming you are passing date objects as parameters.
PopmaticPopmatic
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 farhttps://stackoverflow.com/a/11252167/2091095 . But use +1 to its result if you want the to count all days involved.
Community♦
Dalibor MaturaDalibor Matura
Ruslan López3,09411 gold badge1616 silver badges2828 bronze badges
Abdennour TOUMIAbdennour TOUMI38.4k1515 gold badges154154 silver badges165165 bronze badges
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)
user3806549user380654988011 gold badge1111 silver badges2222 bronze badges
If you have two unix timestamps, you can use this function (made a little more verbose for the sake of clarity):
Example:
Wallace SidhréeWallace Sidhrée7,17833 gold badges3737 silver badges5353 bronze badges
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.
Ramees RahathRamees Rahath
if you wanna have an DateArray with dates try this:
Ricardo FercherRicardo Fercher
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.
Sriman PathySriman Pathy
zloctbzloctb5,32233 gold badges4747 silver badges5858 bronze badges
A Better Solution by
Ignoring time part
it will return 0 if both the dates are same.
Sumit JoshiSumit Joshi58711 gold badge77 silver badges1818 bronze badges
A contribution, for date before 1970-01-01 and after 2038-01-19
Adelson Silva CoutoAdelson Silva Couto
TotPeRo5,33333 gold badges3030 silver badges5050 bronze badges
Parmanand SheteParmanand Shete
You can use UnderscoreJS for formatting and calculating difference.
Demohttps://jsfiddle.net/sumitridhal/8sv94msp/
Sumit RidhalSumit Ridhal65733 gold badges66 silver badges2424 bronze badges
Bookmarklet version of other answers, prompting you for both dates:
drzausdrzaus16.1k77 gold badges9090 silver badges153153 bronze badges
12 next
protected by Community♦Apr 10 at 10:31
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Would you like to answer one of these unanswered questions instead?