TypeScript - compare two dates
In this article, we're going to have a look at how to compare two dates in TypeScript.
Quick solution:
const date1 = new Date(2022, 10, 15);
const date2 = new Date(2022, 10, 15);
console.log(date1.getTime() === date2.getTime()); // true
Â
Talking about date values comparison we need to look at the fact there are comparison operators that will be working and will not directly with date objects:
- Working operators are:
>
,<
,>=
and<=
, - Not working operators are:
==
,===
,!=
andÂ!===
.
For not working operators it is necessary to use getTime()
method and compare results, e.g. date1.getTime() === date2.getTime()
.
Common mistakes analysis:
Note: read this or this article to understans how
==
and===
work for objects comparision.Â
const now = new Date();
const date1 = new Date(now);
const date2 = new Date(now);
console.log( now == now ); // true // incorrect usage !!!
console.log( now === now ); // true // incorrect usage !!!
console.log( date1 == date2 ); // false // incorrect usage !!!
console.log( date1 === date2 ); // false // incorrect usage !!!
console.log( date1 != date2 ); // true // incorrect usage !!!
console.log( date1 !== date2 ); // true // incorrect usage !!!
console.log(date1.getTime() === date2.getTime()); // true // correct usage
Look at the below examples to see how to use comparison operators:
1. Bigger-smaller operators example
In this section presented example uses fact, that it is possible to check that dates are not in relation bigger or smaller, so they are equal.
const compareDates = (a: Date, b: Date): number => {
if (a < b) return -1;
if (a > b) return +1;
return 0; // dates are equal
};
// Usage example:
const now = new Date();
const date1 = new Date(2022, 1, 15);
const date2 = new Date(2022, 6, 20);
console.log(compareDates(now, now)); // 0 // it means dates are equal
console.log(compareDates(date1, date2)); // -1 // arg 1 is smaller (date1 < date2)
console.log(compareDates(date2, date1)); // +1 // arg 1 is bigger (date2 > date1)
Output:
0
-1
1
2. Equal-different operators example
The example presented in this section uses fact, if the Unix time of both dates is equal it means dates are equal.
const compareDates = (a: Date, b: Date): boolean => {
if (a && b) {
return a.getTime() === b.getTime();
}
return false;
};
// Usage example:
const now = new Date();
const date1 = new Date(2022, 1, 15);
const date2 = new Date(2022, 6, 20);
console.log(compareDates(now, now)); // true
console.log(compareDates(date1, date2)); // false
console.log(compareDates(date2, date1)); // false
Output:
true
false
false