Working with dates is one of the most commonly used tasks among the developers of JavaScript. They use date and time handling for scheduling, data validation, etc.
JavaScript provides built-in Date
object to handle everyday use of date and time. It also supports a lot of libraries like Moment.js, Luxon, and Day.js, that provide more functionalities than the built-in Date
object.
Date
objectThe Date
object is created using the new
operator, and we can even initialize by passing the data to the constructor of the Date
. Below is the syntax to create a new object of the Date
type:
const d = new Date()
The Date
object allows the use of comparison operators like <
, <=
, >
, >=
, or =
, and we can compare two dates using these operators. Let’s look at the code, in the code widget below, to compare the two dates. In the code below, we’re creating two variables of the Date
datatype. Then, we use the getDate
method to retrieve the value of the secondDate
, and add 10
to it. After that, we use the setDate
method to set the date value to the secondDate
variable.
let firstDate = new Date();let secondDate = new Date();secondDate.setDate(secondDate.getDate() + 10);// firstDate.setDate(firstDate.getDate() + 10);if (firstDate < secondDate) {console.log(`${firstDate} is less than ${secondDate}`);} else if (firstDate > secondDate) {console.log(`${firstDate} is greater than ${secondDate}`);} else {console.log(`Both dates are equal`);}
Click the “Run” button to execute the code above. We’ll see that the firstDate
, which is less than the secondDate
, will be printed. Now, comment out line 3, uncomment line 4, and execute the code again. This time we’ll see that the firstDate
is greater than secondDate
.
The code above works fine for comparing two dates that are not equal, but what if we want to check the equality of two dates? The equality operators directly don’t work for the Date
object, because JavaScript compares objects by reference, not value. This means that both operands should point to the same memory cell, and only then will the comparison operator identify them as equal. Therefore, we need to convert the Date
objects into the string or numbers. For this, we can use methods of the Date
object. The following methods can be used to convert the Date
object into a number depending upon our use:
getDate()
: This method returns an integer between 1 and 31, describing the day of the date.
getTime()
: This method returns timestamp in milliseconds for the date.
getHours()
: This method returns an integer between 0 and 23, defining the hours of the date as per the local time.
getDay()
: This method returns an integer between 0 and 6 that defines the week’s day number (starting from Sunday), according to the date.
getMonth()
: This method returns an integer between 0 and 11 that defines the month number.
In the code widget below, we’ve equality operators to check if the two dates are equal.
let firstDate = new Date();let secondDate = new Date();// secondDate.setDate(secondDate.getDate() + 10);if (firstDate.getDate() === secondDate.getDate()) {console.log(`${firstDate} is equal to ${secondDate}`);} else if (firstDate.getDate() !== secondDate.getDate()) {console.log(`${firstDate} is not equal to ${secondDate}`);} else {console.log(`Something went wrong`);}
Click the “Run” button to execute the code above, and we’ll see that the first if
condition gets executed. Now, we have to uncomment line 3 and rerun the code. This time, the else if
condition will execute. Now, we understand how to compare dates using the Date
object of JavaScript.
Let’s see how we can compare days and dates using the Moment.js library. We have installed the Moment.js library on our platform. However, if you want to try it on your local environment, use the following command to install it:
npm install moment
Click the “Run” button to execute the following code:
const moment = require('moment')let day1 = moment().format('dddd');let day2 = moment().add(1, 'years').format('dddd');if (day1 === day2){console.log(`After one year this day will be ${day2}.`);}else if (day1 !== day2){console.log(`After one year the day will be ${day2}, but today is ${day1}.`);}else{console.log(`Today is ${day1}, and the next year the day will be ${day2}.`);}
Line 1: We import the moment
library.
Line 3: We use the moment
object that returns the current date, and then we use the format
method to format the date in a day of the week.
Line 4: We use the moment
object, add a year to the current date, and then format it using the format method.
After that, we compare the values and print the relevant output.
In this Answer, we learned two methods to compare dates in JavaScript. We used a built-in Date
object to compare dates and a library for the same purpose. The built-in object usually works well for all cases, but sometimes, we want more flexibility and functionalities to handle complex scenarios. Moment.js extends the capabilities of built-in Date
object, and gives more control over date and time manipulation.
Free Resources