. Advertisement .
. Advertisement .
var day1 = new Date("12/25/2021"); var day2 = new Date("01/5/2022"); var difference = day2.getTime()-day1.getTime(); var difference_day = difference / (1000 * 60 * 60 * 24); console.log(difference_day);
The snippet above creates two Date objects with the new keyword and the Date constructor. We carry out a subtraction by invoking the
getTime() method for both Date objects. The result is an integer value storing the number of milliseconds between those points in time. To convert it to days, we make a series of divisions and print the result to the console.
Remember that there are several ways to indicate your date with the
Date() constructor. In addition to the standard ‘
dd/mm/yyyy‘ string, you can also use other formats like this:
new Date(year, monthIndex, day)
Replace the constructors in the example with these, and you will get the same result:
var day1 = new Date(2021, 12, 25); var day2 = new Date(2022, 1, 5);
Note that many browsers decide to deliberately reduce the precision of time to improve privacy and security by preventing fingerprinting and timing attacks. The precision of the
getTime() gets rounded as a result, depending on the settings.
For instance, Firefox sets this precision to 2ms by default, and you can also change it to 100ms or a bigger value. However, these margins are tiny and should have no impact on the accuracy of your subtraction.
Date.UTC() method acts like the
getTime() method but treats parameters as UTC. Instead of returning a Date object, the method returns the number of milliseconds that have elapsed since that date to the epoch (January 1, 1970, 00:00:00 UTC). It also uses universal time, not local time like the
This is how you can use the
var day1 = new Date("12/25/2021"); var day2 = new Date("01/5/2022"); var dayutc1 = Date.UTC(day1.getFullYear(), day1.getMonth(), day1.getDate()); var dayutc2 = Date.UTC(day2.getFullYear(), day2.getMonth(), day2.getDate()); var difference = dayutc2 - dayutc1; var difference_day = difference / (1000 * 60 * 60 * 24); console.log(difference_day);
Date() constructor, you can use both string and numerical values to specify your date. This means you can rewrite the code above like this:
var dayutc1 = Date.UTC(2021, 12, 25); var dayutc2 = Date.UTC(2022, 1, 5);