How to Calculate the Number of Days Between two Dates in TypeScript ?
Last Updated :
14 Feb, 2024
In TypeScript, calculating the number of days between two dates is a common task in many applications. Whether you’re working with date ranges, scheduling, or performing date-based calculations, knowing how to accurately determine the difference in days between two dates is essential.
Different approaches to achieve this in TypeScript:
Using Two different dates
This approach involves creating Date objects for the two dates you want to compare and then calculating the difference in milliseconds between them. Afterward, you can convert this difference into days.
Syntax :
const date: Date = new Date("//date you want")
Example: The following JavaScript program will illustrate the process of finding the number of days between two dates.
Javascript
const date1: Date = new Date( '2024-01-15' );
const date2: Date = new Date( '2024-02-06' );
const differenceInMs: number =
Math.abs(date2.getTime() - date1.getTime());
const millisecondsInDay: number = 1000 * 60 * 60 * 24;
const differenceInDays: number =
Math.floor(differenceInMs / millisecondsInDay);
console.log(
'Number of days between the two dates:' , differenceInDays);
|
Output :
Number of days between the two dates: 22
Using moment.js library
This method provides a convenient and concise way to calculate the number of days between two dates using moment.js, a popular library for date manipulation in JavaScript and TypeScript, for using moment.js library one need to install and configure node.js and then install the moment package in order to use.
Syntax:
npm install moment
import * as moment from 'moment';
Example: The following JavaScript program will illustrate the process of finding the number of days between two dates.
Javascript
import * as moment from 'moment' ;
function daysBetweenDates(date1: string, date2: string): number {
const startMoment = moment(date1);
const endMoment = moment(date2);
const daysDifference =
endMoment.diff(startMoment, 'days' );
return daysDifference;
}
const startDate = '2024-01-01' ;
const endDate = '2024-02-08' ;
const daysDifference =
daysBetweenDates(startDate, endDate);
console.log(
"Number of days between the two dates:" , daysDifference);
|
Output:
Number of days between the two dates: 38
Share your thoughts in the comments
Please Login to comment...