- Compare Dates in JavaScript
- Before and After
- Sorting
- More Fundamentals Tutorials
- JavaScript Date Comparison – How to Compare Dates in JS
- How to Perform Date Comparison With the Date Object in JavaScript
- How to Perform Equality Comparison With JavaScript
- How to Perform Specific Date Comparisons
- Conclusion
- Compare Two Dates in JavaScript
- The Date Object in JavaScript
- Comparing Two Dates in JavaScript
- Free eBook: Git Essentials
- Conclusion
Compare Dates in JavaScript
How do you compare if two dates are equal? Surprisingly, both triple equals and double equals don’t work when comparing two dates.
const d1 = new Date('2019-06-01'); const d2 = new Date('2018-06-01'); const d3 = new Date('2019-06-01'); d1 === d3; // false d1 == d3; // false
To compare two dates, you can use either toString() or valueOf() . The toString() method converts the date into an ISO date string, and the valueOf() method converts the date into milliseconds since the epoch.
const d1 = new Date('2019-06-01'); const d2 = new Date('2018-06-01'); const d3 = new Date('2019-06-01'); // 'Fri May 31 2019 20:00:00 GMT-0400 (Eastern Daylight Time)' d1.toString(); d1.valueOf(); // 1559347200000 d1.toString() === d2.toString(); // false d1.toString() === d3.toString(); // true d1.valueOf() === d2.valueOf(); // false d1.valueOf() === d3.valueOf(); // true
Before and After
Although neither == nor === can compare whether two dates are equal, surprisingly both < and >work fine for comparing dates:
d1 < d2; // false d1 < d3; // false d2 < d1; // true
So to check if date a is before date b , you can just check a < b .
Another neat trick: you can subtract dates in JavaScript. Subtracting a — b gives you the difference between two dates in milliseconds.
const d1 = new Date('2019-06-01'); const d2 = new Date('2018-06-01'); const d3 = new Date('2019-06-01'); d1 - d3; // 0 d1 - d2; // 1 year in milliseconds, 1000 * 60 * 60 * 24 * 365
In other words, you can compare two dates a and b by using a — b . If b is after a , then a — b < 0 .
Sorting
Sorting an array of dates in JavaScript doesn’t work as you might expect. The below sort() call gives you the dates in reverse order.
const d1 = new Date('2017-06-01'); const d2 = new Date('2018-06-01'); const d3 = new Date('2019-06-01'); [d2, d1, d3].sort(); // [d3, d2, d1]
Why is that? Because JavaScript’s sort function implicitly converts all values in the array into strings before sorting. So the above sort() is actually sorting based on the below string values:
[ 'Fri May 31 2019 20:00:00 GMT-0400 (Eastern Daylight Time)', 'Thu May 31 2018 20:00:00 GMT-0400 (Eastern Daylight Time)', 'Wed May 31 2017 20:00:00 GMT-0400 (Eastern Daylight Time)' ]
In other words, JavaScript implicitly sorts arrays of dates based on the day of the week by default.
To sort dates based on which date happened first, you need to pass a compare() callback to the sort() function. The compare() function should return:
Since JavaScript lets you subtract dates, you can just use a — b as your comparison function:
const d1 = new Date('2017-06-01'); const d2 = new Date('2018-06-01'); const d3 = new Date('2019-06-01'); [d2, d1, d3].sort((a, b) => a - b); // [d1, d2, d3]
More Fundamentals Tutorials
JavaScript Date Comparison – How to Compare Dates in JS
Joel Olawanle
A date is one of the most common datatypes developers use when creating real-world applications.
But often, devs struggle with this datatype and end up using date libraries like Moment.js for simple tasks that aren’t worth the large package size that comes with installing an entire package.
In this article, we will learn how to perform date comparisons in JavaScript. If you need the code quickly, here it is:
const compareDates = (d1, d2) => < let date1 = new Date(d1).getTime(); let date2 = new Date(d2).getTime(); if (date1 < date2) < console.log(`$is less than $`); > else if (date1 > date2) < console.log(`$is greater than $`); > else < console.log(`Both dates are equal`); >>; compareDates("06/21/2022", "07/28/2021"); compareDates("01/01/2001", "01/01/2001"); compareDates("11/01/2021", "02/01/2022");
"06/21/2022 is greater than 07/28/2021" "Both dates are equal" "11/01/2021 is less than 02/01/2022"
When we think of date comparison in JavaScript, we think of using the Date object ( Date() ) and, of course, it works.
The date object allows us to perform comparisons using the > , < , = , or >= comparison operators, but not the equality comparison operators like == , != , === , and !== (unless we attach date methods to the date Object).
Let’s begin by learning how to perform comparisons using only the date object, and then we’ll see how to perform equality comparisons using the date object alongside date methods.
How to Perform Date Comparison With the Date Object in JavaScript
Suppose we want to compare two dates in JavaScript. We can easily use the Date Object ( Date() ) this way:
let date1 = new Date(); let date2 = new Date(); if (date1 > date2) < console.log("Date 1 is greater than Date 2"); >else if (date1 < date2) < console.log("Date 1 is less than Date 2"); >else
The above will return that both dates are the same because we didn’t pass different dates:
Let’s now pass in different date values:
let date1 = new Date(); let date2 = new Date("6/01/2022"); if (date1 > date2) < console.log("Date 1 is greater than Date 2"); >else if (date1 < date2) < console.log("Date 1 is less than Date 2"); >else
This will now return the following:
"Date 1 is greater than Date 2"
Fortunately, the above handles equality as the last option when the first two conditions fail. But suppose we try to handle equality as the condition this way:
let date1 = new Date(); let date2 = new Date(); if (date1 === date2) < console.log("Both Dates are same"); >else
It will return the following, which is wrong:
How to Perform Equality Comparison With JavaScript
To handle equality comparison, we use the date object alongside the getTime() date method which returns the number of milliseconds. But if we want to compare specific information like day, month, and so on, we can use other date methods like the getDate() , getHours() , getDay() , getMonth() and getYear() .
let date1 = new Date(); let date2 = new Date(); if (date1.getTime() === date2.getTime()) < console.log("Both are equal"); >else
We can pass in different dates into the date object so as to compare:
let date1 = new Date("12/01/2021"); let date2 = new Date("09/06/2022"); if (date1.getTime() === date2.getTime()) < console.log("Both are equal"); >else
As expected this will return:
Note: With the getTime() method we can perform all forms of date comparison using all comparison operators, which are > , < , = , == , != , === , and !== .
How to Perform Specific Date Comparisons
Suppose we want to compare specific date values like the year. Then we can use the .getYear() date method this way:
let date1 = new Date("06/21/2022").getYear(); let date2 = new Date("07/28/2021").getYear(); if (date1 < date2) < console.log("Date1 is less than Date2 in terms of year"); >else if (date1 > date2) < console.log("Date1 is greater than Date2 in terms of year"); >else
Conclusion
In this article, you have learned how to do date comparisons in JavaScript using the date Object without having to install any library.
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.
Compare Two Dates in JavaScript
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(`$ is greater than $ `) > else if(date1 < date2)< console.log(`$ is greater than $ `) > else< console.log(`Both dates are equal`) > > dateCompare("6/11/2020", "7/8/2019") dateCompare("01/01/2021", "01/01/2021")
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(`$ is greater than $ in terms of milliseconds`) > else if(date1.getYear() < date2.getYear())< console.log(`$ is greater than $ 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")
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.
Free eBook: Git Essentials
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!
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")
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.