How to Compare Two Date Strings in TypeScript ?
Last Updated :
16 Jul, 2024
In TypeScript, we can compare two date strings by converting them to comparable formats using Date objects or by parsing them into the timestamps. We will discuss different approaches with the practical implementation of each one of them.
Using Date Objects
In this approach, we are using Date objects to parse the input date strings. We then compare their time values using getTime(), and based on the comparison, we print whether the first date is equal to, earlier than, or later than the second date.
Syntax:
const res: Date = new Date();
Example: The below example uses Date Objects to compare two date strings in TypeScript.
JavaScript
const dStr1: string = "2022-02-27";
const dStr2: string = "2024-02-27";
const d1: Date = new Date(dStr1);
const d2: Date = new Date(dStr2);
if (d1.getTime() === d2.getTime()) {
console.log(`${dStr1} is equal to ${dStr2}`);
} else if (d1.getTime() < d2.getTime()) {
console.log(`${dStr1} is earlier than ${dStr2}`);
} else {
console.log(`${dStr2} is earlier than ${dStr1}`);
}
Output:
2022-02-27 is earlier than 2024-02-27
Using Date.parse
In this approach, we are using the Date.parse method to convert the input date strings into timestamps. We then compare these timestamps and print whether the first date is equal to, earlier than, or later than the second date.
Syntax:
const res: number = Date.parse(dateString);
Example: The below example uses Date.parse to compare two date strings in TypeScript.
JavaScript
const dStr1: string = '2022-02-27';
const dStr2: string = '2024-02-27';
const t1: number = Date.parse(dStr1);
const t2: number = Date.parse(dStr2);
if (t1 === t2) {
console.log(`${dStr1} is equal to ${dStr2}`);
} else if (t1 < t2) {
console.log(`${dStr1} is earlier than ${dStr2}`);
} else {
console.log(`${dStr2} is earlier than ${dStr1}`);
}
Output:
2022-02-27 is earlier than 2024-02-27
In this approach, we are using Intl.DateTimeFormat to create a formatter with specific date formatting options for the 'en-US' locale. We then format the input date strings using this formatter. The formatted dates are compared, and based on the comparison, we print whether the first date is equal to, earlier than, or later than the second date.
Syntax:
const formatter: Intl.DateTimeFormat =
new Intl.DateTimeFormat(locales, options);
Example: The below example uses Intl.DateTimeFormat to compare two date strings in TypeScript.
JavaScript
const dStr1: string = '2024-02-27';
const dStr2: string = '2024-02-27';
const temp = new Intl.DateTimeFormat('en-US',
{
year: 'numeric', month: '2-digit',
day: '2-digit'
});
const d1 = temp.format(new Date(dStr1));
const d2 = temp.format(new Date(dStr2));
if (d1 === d2) {
console.log(`${dStr1} is equal to ${dStr2}`);
} else if (d1 < d2) {
console.log(`${dStr1} is earlier than ${dStr2}`);
} else {
console.log(`${dStr2} is earlier than ${dStr1}`);
}
Output:
2024-02-27 is equal to 2024-02-27
Using a Custom Date Comparison Function
In this approach, a custom function is implemented to compare two date strings based on specific requirements or formats. This approach provides flexibility to tailor the comparison logic according to the application's needs.
Syntax:
function compareDates(dateString1: string, dateString2: string): number {
// Custom comparison logic
}
Example: In this example Function compareDates compares two date strings, returning 0 if equal, -1 if first is earlier, and 1 if later. It then logs the comparison result.
JavaScript
function compareDates(dateString1: string, dateString2: string): number {
const date1: Date = new Date(dateString1);
const date2: Date = new Date(dateString2);
if (date1.getTime() === date2.getTime()) {
return 0; // Dates are equal
} else if (date1.getTime() < date2.getTime()) {
return -1; // First date is earlier than the second date
} else {
return 1; // First date is later than the second date
}
}
const dStr1: string = '2024-02-27';
const dStr2: string = '2024-02-27';
const comparisonResult: number = compareDates(dStr1, dStr2);
if (comparisonResult === 0) {
console.log(`${dStr1} is equal to ${dStr2}`);
} else if (comparisonResult < 0) {
console.log(`${dStr1} is earlier than ${dStr2}`);
} else {
console.log(`${dStr2} is earlier than ${dStr1}`);
}
Output:
2024-02-27 is equal to 2024-02-27
Using Moment.js Library
In this approach, we utilize the Moment.js library, a popular library for parsing, validating, manipulating, and formatting dates in JavaScript. Moment.js provides a straightforward way to compare dates by converting them into Moment objects and using the comparison methods provided by the library.
Example: The following example demonstrates how to compare two date strings using the Moment.js library in TypeScript.
JavaScript
import * as moment from 'moment';
function compareDatesUsingMoment(dateString1: string, dateString2: string): void {
const date1 = moment(dateString1);
const date2 = moment(dateString2);
if (date1.isSame(date2)) {
console.log(`${dateString1} is equal to ${dateString2}`);
} else if (date1.isBefore(date2)) {
console.log(`${dateString1} is earlier than ${dateString2}`);
} else {
console.log(`${dateString1} is later than ${dateString2}`);
}
}
const dateStr1 = "2022-02-27";
const dateStr2 = "2024-02-27";
compareDatesUsingMoment(dateStr1, dateStr2);
Output:
2022-02-27 is earlier than 2024-02-27
Similar Reads
How to Convert String to Date in TypeScript ?
In TypeScript, conversion from string to date can be done using the Date object and its method. We can use various inbuilt methods of Date object like new Date() constructor, Date.parse(), and Date.UTC. Table of Content Using new Date()Using Date.parse() Using Date.UTC()Using new Date()In this appro
2 min read
How to create conditional types in TypeScript ?
Conditional types in TypeScript enable defining types based on conditions, similar to conditional statements in code. They determine different types of values, making functions adaptable to various input types, and enhancing code flexibility and maintainability. Syntax: We can create conditional typ
3 min read
How to Create an Enum With String Values in TypeScript ?
To create an enum with string values in TypesScript, we have different approaches. In this article, we are going to learn how to create an enum with string values in TypesScript. Below are the approaches used to create an enum with string values in TypesScript: Table of Content Approach 1: Using Enu
3 min read
How to express a Date Type in TypeScript ?
In TypeScript, the Date object is used to handle dates and times. To express a Date type, declare a variable with the type annotation Date and assign it a date value. This allows for precise date manipulation and formatting in your TypeScript code. Ways to Express Date Type in TypeScriptTable of Con
3 min read
How to Format Date in TypeScript ?
Formatting dates is important especially when displaying them to the users or working with date-related data. TypeScript provides various ways to achieve this. Below are the methods to format the date data type in TypeScript: Table of Content Using toLocaleString() methodUsing toLocaleDateString() m
4 min read
How to Test if Two Types are Exactly the Same in TypeScript ?
This article will show how we can test if the two types are the same in TypeScript. Types in Typescript are used to define and describe the data in our code. Some of the types are number, string, boolean, etc. Below are the possible approaches: Table of Content Using extends and keyofUsing Extract a
3 min read
How to Calculate the Time Between 2 Dates in TypeScript ?
In this article, we will calculate the time between two different dates using TypeScript. We will use the getTime() method to get the current time of the specified date. Syntax:const variable_name = new Date();const time = variable_name.getTime();Note: The getTime() method will return the time in th
2 min read
How To Compare Only Date In Moment.js?
In Moment.js, date manipulation and parsing can be done efficiently. Along with this, the library provides ways to compare only the date portion of two date objects, ignoring the time component. Methods like startOf, isSame, and formatting techniques enable you to focus solely on the date part for a
3 min read
How to Compare Dates with Moment.js?
Moment.js is a popular JavaScript library that developers use for parsing, manipulating, and formatting dates and times. It provides a range of methods to compare dates, making it easier to handle various date-related tasks. With Moment.js, you can use methods like isBefore, isAfter, diff, and isSam
3 min read
How to Sort a Numerical String in TypeScript ?
To sort numerical string in TypeScript, we could use localCompare method or convert numerical string to number. Below are the approaches used to sort numerical string in TypeScript: Table of Content Using localeCompareConverting to Numbers before sortingApproach 1: Using localeCompareThe localeCompa
2 min read