For over 5+ years we help companies reach their financial and branding goals. oDesk Software Co., Ltd is a values-driven technology agency dedicated

Gallery

Contacts

Address

108 Tran Dinh Xu, Nguyen Cu Trinh Ward, District 1, Ho Chi Minh City, Vietnam

E-Mail Address

info@odesk.me

Phone

(+84) 28 3636 7951

Hotline

(+84) 76 899 4959

Websites Development

Everything You Should Know about Comparing Dates in Javascript

Dates are hard, let’s learn how to compare them

Working with dates is something developers encounter very often. From creating to storing and processing dates, date manipulation in Javascript has many use cases in application development. In today’s tutorial, we thought to focus on one of them: comparing dates.

Javascript’s built-in date object gives us enough functionality to compare dates, especially for finding quick and simple solutions. At the end of this tutorial, though, we will look a little into how to compare dates in Javascript with the help of a third-party library.

Can we use the logical operators for date comparison?

Does Javascript’s date object support comparison between dates using logical operators like <>===, and ==? That’s what we are going to find out in this section.

As it turns out, comparing Javascript dates using less than (<) and greater than (>) operators is one of the most straightforward solutions to this problem, as the following example shows.

const date1 = new Date("2021-01-31")
const date2 = new Date("2021-04-21")
const date3 = new Date("2021-05-09")

console.log(date1 > date2) //false
console.log(date1 < date2) //true
console.log(date2 < date3) //true
console.log(date2 > date3) //false

But when we use equal operators to check whether two dates are the same, neither == or === returns the correct results for two equal dates.

const date1 = new Date("2021-01-31")
const date2 = new Date("2021-04-21")
const date3 = new Date("2021-01-31")

console.log(date1) //2021-01-31T00:00:00.000Z
console.log(date2) //2021-04-21T00:00:00.000Z
console.log(date3) //2021-01-31T00:00:00.000Z

console.log(date1 == date2) //false
console.log(date1 === date2) //false
console.log(date1 == date3) //false
console.log(date1 === date3) //false
console.log(date1 !== date3) //true
console.log(date1 != date3) //true

This behavior is a result of the underlying nature of Javascript. In Javascript, two distinct objects can’t ever be equal whether you’re using the strict (===) or abstract equality (==) operator.

So, when you want to cover all three bases of date comparison, you have to use a different method than logical operators to get the right results.

Date-time comparison with getTime method

So, as an alternative way to compare dates with time in Javascript, we can use the date object’s built-in method, getTime. The getTime method returns the number of milliseconds elapsed since epoch time (1st January 1970 00:00:00 (UTC)) to the date-time represented by the date object. This paves for a simpler numeric comparison between two dates where we can use all logical operators without any strange behaviors.

Here’s an example of getTime method in action.

const date1 = new Date("2021-01-31")
const date2 = new Date("2021-04-21")
const date3 = new Date("2021-01-31")

console.log(date1.getTime() > date2.getTime()) //false
console.log(date1.getTime() < date2.getTime()) //true
console.log(date1.getTime() === date3.getTime()) //true
console.log(date1.getTime() !== date3.getTime()) //false

A bonus to using getTime method over direct date object comparisons is that it’s works faster than the alternative.

Date-time comparison with valueOf

Another date comparison method in Javascript is valueOf. This method also returns the elapsed number of milliseconds since epoch time. Here’s how we can use this in our code.

console.log(date1.valueOf() > date2.valueOf()) //false
console.log(date1.valueOf() < date2.valueOf()) //false
console.log(date1.valueOf() === date3.valueOf()) //true
console.log(date1.valueOf() !== date3.valueOf()) //false

Date only comparisons in Javascript

So far, all our examples considered the time component of the date when comparing dates. But can we compare only the date parts of date objects in Javascript? The answer is yes.

But since Javascript doesn’t provide a built-in method to carry out this type of comparison directly, we have to get help from a few other functions to reach the end result we’re looking for.

In short, we have to extract the year, month, and date of the month components from the initial objects separately to compare dates without time.

In the following example, we share a method that checks equality between two dates with the help of getFullYear, getMonth, getDate built-in Javascript methods.

function isDateEqual(date1, date2) {
    return date1.getFullYear() === date2.getFullYear() &&
        date1.getMonth() === date2.getMonth() &&
        date1.getDate() === date2.getDate()
}

const date1 = new Date("2021-01-31T09:11:12Z")
const date2 = new Date("2021-04-21T12:10:34Z")
const date3 = new Date("2021-01-31T03:34:23Z")

console.log(isDateEqual(date1, date2))
console.log(isDateEqual(date1, date3))

As an alternative to the above solution, we can change the time part of a date object to a shared value before using the getTime or valueOf method to compare dates, which prevents its time value from impacting the outcome.

If your use case is something that won’t be impacted by changes to initial data, you can easily carry out the comparisons like the following example shows. Otherwise, you have the option to clone the initial object and go forward with this implementation.

const date1 = new Date("2021-01-31T09:11:12Z")
const date2 = new Date("2021-04-21T12:10:34Z")
const date3 = new Date("2021-01-31T03:34:23Z")

date1.setHours(0, 0, 0, 0)
date2.setHours(0, 0, 0, 0)
date3.setHours(0, 0, 0, 0)

console.log(date1.getTime() > date2.getTime()) //false
console.log(date1.getTime() < date2.getTime()) //true
console.log(date1.getTime() === date3.getTime()) //true
console.log(date1.getTime() !== date3.getTime()) //false

We can also extract only the date part of an object using the toDateString method to compare dates without time. Here’s how you can achieve that.

date1 = new Date(date1.toDateString())
date2 = new Date(date2.toDateString())
date3 = new Date(date3.toDateString())

console.log(date1.getTime() > date2.getTime()) //false
console.log(date1.getTime() < date2.getTime()) //true
console.log(date1.getTime() === date3.getTime()) //true
console.log(date1.getTime() !== date3.getTime()) //false

Taking timezones into consideration

One thing we have to be very careful when working with dates in Javascript is timezone differences. It’s true even when we are comparing dates. So, what impact do timezones have on everything we did so far?

In comparisons using getTime and valueOf methods, Javascript measures time in relation to its epoch time, which is in UTC. So, even if we compare two dates created in two timezones, these methods output the correct results we expect to see.

const date1 = new Date("2021-01-31T09:11:12+05:00")
const date2 = new Date("2021-01-31T05:11:12+01:00")

console.log(date1.getTime() === date2.getTime()) //true

But when we are comparing dates without time components after selectively picking year, month, and date (like in the isDateEqual function), we have to be conscious about the effect timezones have on the process. In that case, without directly extracting date components from the object, first, we have to convert them to UTC.

let date1 = new Date("2021-01-31T09:11:12+05:00")
let date2 = new Date("2021-01-31T05:11:12+01:00")

date1 = new Date(Date.UTC(date1.getUTCFullYear(), date1.getUTCMonth(), date1.getUTCDate()))
date2 = new Date(Date.UTC(date2.getUTCFullYear(), date2.getUTCMonth(), date2.getUTCDate()))

console.log(date1.getTime() === date2.getTime()) //true
console.log(date1.getTime() !== date2.getTime()) //false

Comparing dates with date-fns

So far, we have only relied on Javascript’s native date object to compare dates. Even though it provided sufficient methods to execute basic comparisons, we had to use several lines of code to implement something more advanced, like comparing dates without time.

Third-party date manipulation libraries like date-fns, however, come with dedicated methods that allow us to solve these problems with a single line of code. So, we thought it would be a good idea to see how to execute date comparisons in Javascript with the help of the date-fns library.

We can use date-fns’ isAfter, isBefore, isEqual methods to check whether two dates are equal, greater than, or less than, as the following example shows.

let date1 = new Date("2021-01-31T09:11:12Z")
let date2 = new Date("2021-04-21T12:10:34Z")
let date3 = new Date("2021-01-31T05:11:12Z")

//Is first date after the second one
console.log(datefns.isAfter(date1, date2)) //false
console.log(datefns.isAfter(date2, date1)) //true

//Is first date before the second one
console.log(datefns.isAfter(date1, date3)) //true
console.log(datefns.isAfter(date3, date1)) //false

//Is first date equal to second one
console.log(datefns.isEqual(date1, date3)) //true
console.log(datefns.isEqual(date1, date2)) //false

For comparisons without taking time into account, we can use the isSameDay function like this:

console.log(datefns.isSameDay(date1, date3)) //true
console.log(datefns.isSameDay(date1, date2)) //false

That’s it! We can find the answer to our problem by calling a single function.

Summary

In today’s tutorial, we walked you through how to compare dates in Javascript. Although the native Javascript object gives us sufficient functionality to handle this task, if you have to carry out different comparison operations in your app, using a third-party library can simplify your implementation and clean up the code.

No matter which way of date comparison you prefer, we hope you liked our post and learned something new today that you’d find useful in your next projects.

Thank you for reading!

Source: livecodestream

Author

oDesk Software

Leave a comment