Introduction
Dates are a really common data type developers work with. From timestamps of certain actions, to reports, sign up features and limited-time access in systems that require subscriptions - we oftentimes have to compare dates.
That is, we compare if a date is after or before another, if the date is today, how many days there are between dates, etc.
In this article, we'll take a look at how to compare two dates in JavaScript, helping us deduce whether a date is before or after another.
The Date Object in JavaScript
Web developers commonly use external packages (like Moment.js) to handle date-time operations. But, as the modern web evolved, JavaScript introduced a new object constructor called Date
to handle date-time operations.
This means that you don't need an external library to perform rudimentary checks and operations, which makes it easier to perform these things in Vanilla JS.
The Date
class is really simple to understand under the hood - it just stores Unix time measured in milliseconds.
Unix time is measured as the number of seconds elapsed since the Unix epoch (00:00:00 UTC 1 January 1970), which is a completely arbitrary date.
Even though this implementation seems a bit simplistic, the addition of the Date
class was quite a big improvement, since there was finally a level of abstraction between developers and raw dates.
Now, let's look at different ways to compare two dates using Date
objects.
Comparing Two Dates in JavaScript
We can use comparison operators like <
and >
to compare two Date
objects, and under the hood, their time counters are effectively compared. You're effectively comparing two integer counters:
function dateCompare(d1, d2){
const date1 = new Date(d1);
const date2 = new Date(d2);
if(date1 > date2){
console.log(`${d1} is greater than ${d2}`)
} else if(date1 < date2){
console.log(`${d2} is greater than ${d1}`)
} else{
console.log(`Both dates are equal`)
}
}
dateCompare("6/11/2020", "7/8/2019")
dateCompare("01/01/2021", "01/01/2021")
This results in:
6/11/2020 is greater than 7/8/2019
Both dates are equal
As we can see, comparing dates just boils down to converting the provided strings into Date
objects and comparing them with an appropriate comparison operator.
Note: Equality operators (==
and ===
) don't work with Date
objects, so we don't explicitly check if they're the same.
Another way to compare two dates is by using the built-in getTime()
method.
The getTime()
method returns the number of milliseconds elapsed since the Unix epoch. Additionally, you can use the, getDate()
, getHours()
, getDay()
, getMonth()
and getYear()
methods to further specify and compare information, amongst other similarly named methods.
Additionally, you can also use the getUTCDay()
, getUTCDate()
, getUTCHour()
, getUTCMinute()
, etc. methods, which return the given temporal identifiers, zoned specifically to UTC.
Note that with this approach, you can use equality operators!
Let's take a look at an example:
function compareDates(d1, d2){
const date1 = new Date(d1);
const date2 = new Date(d2);
if(date1.getTime() > date2.getTime()){
console.log(`${d1} is greater than ${d2} in terms of milliseconds`)
} else if(date1.getYear() < date2.getYear()){
console.log(`${d2} is greater than ${d1} in terms of years`)
} else if(date1.getDate() === date2.getDate()){
console.log(`Both dates are equal`)
}
}
compareDates("9/10/1997", "9/10/2000")
compareDates("11/11/2021", "11/1/2021")
This results in:
9/10/2000 is greater than 09/10/1997 in terms of years
11/11/2021 is greater than 11/1/2021 in terms of milliseconds
Though, since we're working with if
and if-else
blocks, some statements never get to execute. For example, 9/10/1997
and 9/10/2000
have the same date, the 9/10
, though, not the same year.
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
For example, this code:
function compareDates(d1, d2){
const date1 = new Date(d1);
const date2 = new Date(d2);
if(date1.getDate() === date2.getDate()){
console.log(`Both dates are equal`)
}
}
compareDates("09/10/1997", "9/10/2000")
Would result in:
Both dates are equal
Since we're just comparing the date, without the year in mind.
Conclusion
In this article, we've briefly gone over how JavaScript handles dates using Date
objects. Then, we've covered how to compare dates in JavaScript, keeping some useful methods in mind.