In this post we cover how to calculate the number of days between two dates in JavaScript
How to calculate the number of days between two dates in JavaScript
The easiest way to calculate the number of days between two dates in JavaScript would be to use a Date library such as date-fns
.
By using the date-fns
library it is possible to calculate the number of days between two dates like so:
1import { differenceInDays } from "date-fns";
2
3const dateA = new Date("02/05/2023"); // MM/DD/YYYY
4const dateB = new Date("02/15/2023"); // MM/DD/YYYY
5
6differenceInDays(dateA, dateB); // 10
Alternatively it is possible to calculate the difference in days between two dates in VanillaJS as well but it involves some additional code.
Here is one way to calculate the number of days between two dates in JavaScript with vanillaJS:
1const msToDays = ms => {
2 const MS_IN_ONE_SECOND = 1000;
3 const SECONDS_IN_ONE_MIN = 60;
4 const MINS_IN_ONE_HOUR = 60;
5 const HOURS_IN_ONE_DAY = 24;
6
7 const minutesInOneDay = HOURS_IN_ONE_DAY * MINS_IN_ONE_HOUR;
8 const secondsInOneDay = SECONDS_IN_ONE_MIN * minutesInOneDay;
9 const msInOneDay = MS_IN_ONE_SECOND * secondsInOneDay;
10
11 return Math.ceil(ms / msInOneDay);
12};
13
14const differenceInDays = (dateA, dateB) => {
15 let differenceInMs = dateB.getTime() - dateA.getTime();
16
17 return convertMsToDays(differenceInMs)
18};
19
20const dateA = new Date("02/05/2023"); // MM/DD/YYYY
21const dateB = new Date("02/15/2023"); // MM/DD/YYYY
22
23getDaysBetweenDates(dateA, dateB); // 10
JavaScript
JavaScript is a programming language that is primarily used to help build frontend applications.
It has many uses, such as making network requests, making dynamic or interactive pages, creating business logic and more.
VanillaJS
VanillaJS is a term often used to describe plain JavaScript without any additions, libraries or frameworks.
In other words when writing with VanilliaJS you are simply writing JavaScript as it comes out of the box.
JavaScript Date Object
The JavaScript Date Object is used to capture a moment in time and to be able to use this time programatically.
Further resources
Related topics
Save code?