JavaScript
Date arithmetic
Learn to compute the difference between two dates and compare dates using timestamps.
Date arithmetic
To find the difference between two dates you use their timestamps. getTime returns the timestamp in milliseconds.
const a = new Date('2024-01-01');
const b = new Date('2024-02-01');
const diff = b.getTime() - a.getTime();
diff is the difference in milliseconds. To convert it to days you divide by the number of milliseconds in a day. This is the basis of date comparison.
Converting to days and comparing
One day is 24 * 60 * 60 * 1000 milliseconds. Divide the difference by this number and round down with Math.floor.
const MS_PER_DAY = 24 * 60 * 60 * 1000;
const days = Math.floor(diff / MS_PER_DAY);
Math.floor drops the fraction so you get the whole number of days. You can also compare two dates by their getTime values; JavaScript converts dates to timestamps automatically.
Exercise Compute the day difference between two dates
start and end are two dates. Assign 24 * 60 * 60 * 1000 to MS_PER_DAY, get the difference with getTime, convert it to days with Math.floor and log it with console.log.
Show example solution
Subtracting two dates gives the millisecond difference; getTime returns a timestamp. One day has 24*60*60*1000 milliseconds; divide the difference by that and round down with Math.floor.
Example solution:
const start = new Date('2024-01-01');
const end = new Date('2024-02-01');
const MS_PER_DAY = 24 * 60 * 60 * 1000;
const diffMs = end.getTime() - start.getTime();
const days = Math.floor(diffMs / MS_PER_DAY);
console.log(days);
Test yourself
-
What is the first step to find the difference between two dates in days?
- Get the difference in milliseconds, then divide by the day count
- Subtract the month difference directly
- Get the weekday with getDay
- Compare with toISOString
Show answer
Get the difference in milliseconds, then divide by the day count — Correct! First get the difference in milliseconds and divide by the milliseconds per day.
-
Milliseconds in a day
const MS_PER_DAY = ____;
Show answer
const MS_PER_DAY = 24 * 60 * 60 * 1000;
-
Match the arithmetic parts
- getTime()
- gives timestamp
- date1 - date2
- diff in ms
- 24*60*60*1000
- ms per day
- Math.floor()
- rounds down
Next lesson: Summary - Date and time