You have two main options:
- Use an npm package1 like luxon, day.js, or date-fns
- Convert each date to milliseconds, subtract, and multiply
Let’s go through a quick example of each approach.
Using date-fns
to get date difference
Above, I mentioned luxon
, day.js
, and date-fns
. They’re all great packages, but I personally prefer date-fns
due to its easily searchable documentation.
const {
differenceInDays,
differenceInHours,
differenceInMinutes,
} = "date-fns";
const twentyThree = new Date("2023/01/01");
const twentyTwo = new Date("2022/01/01");
differenceInDays(twentyThree, twentyTwo);
// 365
differenceInHours(twentyThree, twentyTwo);
// 8760
differenceInMinutes(twentyThree, twentyTwo);
// 525600
date-fns
has a ton of other functionality and the docs are very good (and searchable!), I’d recommend using it.
Using pure javascript
This is a bit more convoluted, but doesn’t require any additional packages. It does, however, require a bit of knowledge of what Unix Time is. To plagiarize wikipedia:
Unix Time […] measures time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970, the beginning of the Unix epoch, less adjustments made due to leap seconds.
Now that you know that, let’s get into it:
const twentyThree = new Date("2023/01/01");
const twentyTwo = new Date("2022/01/01");
// Convert both dates to millisecond Unix time
// I know I said "seconds" above, but JS does it in MS ¯\_(ツ)_/¯
const twentyThreeMs = twentyThree.getTime();
const twentyTwoMs = twentyTwo.getTime();
// calculate the difference
const diffMs = twentyThreeMs - twentyTwoMs;
const msPerDay = 1000 * 60 * 60 * 24;
// 1000 ms per second
// 60 seconds per minute
// 60 minutes per hour
// 24 hours per day
const differenceInDays = diffMs / msPerDay;
// 365
const msPerHour = 1000 * 60 * 60;
const differenceInHours = diffMs / msPerHour;
// 8760
// Minutes
console.log(diffMs / 60000);
// 525600
Not too bad, even in plain JS. In larger projects though, there’s a good chance you’ll be doing other operations on dates, and a nice npm package like date-fns
will definitely make your life easier.
Notes
- For years, moment.js was the be-all and end-all of javascript date manipulation. However, it’s now in maintenance mode, and moment’s maintainers themselves recommend the three alternatives posted above. ↩︎
Helpful Links
What is Epoch (Unix) Time? – wikipedia