How to calculate the number of days between two dates?
P粉604848588
2023-08-23 16:51:49
<p>For example, two dates are given in the input box: </p>
<pre class="brush:php;toolbar:false;"><input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
<script>
alert(datediff("day", first, second)); // what goes here?
</script></pre>
<p>How to get the number of days between two dates in JavaScript? </p>
As of this writing, only one of the other answers correctly handles DST (Daylight Savings Time) conversion. Here are the results on a system located in California:
Although
Math.round
returns the correct result, I think it's a bit clunky. Instead, by explicitly accounting for the change in UTC offset when DST starts or ends, we can use precise arithmetic:illustrate
JavaScript date calculations are tricky because
Date
objects internally store UTC time, 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) stored as 3/11/2013 7:00 AM UTC. On this day, local time from midnight to midnight is only 23 hours ahead of UTC!While a day in local time can be more or less than 24 hours long, a day in UTC is always exactly 24 hours long. 1 The
daysBetween
method shown above takes advantage of this by first callingtreatAsUTC
to adjust both local times to midnight UTC, then subtracting and dividing. This fact.1. JavaScript ignores leap seconds.
Here is a
quick and dirty
implementation of datediff as a proof of concept for solving the problem posed in the question. It relies on the fact that you can get the number of milliseconds that elapsed between two dates by subtracting them, which coerces them to their original numerical values (number of milliseconds since early 1970).