How to check if a date is today in JavaScript

From a JavaScript date instance, we can get the day, month and year values by using getDate(), getMonth() and getFullYear() methods:

// month is zero-based (0-11)
const date = new Date(2022, 7, 7)

date.getDate() // 7
date.getMonth() // 7
date.getFullYear() // 2022

Now let's create a small function that takes a date as an argument and compares the above values to today's date values, and returns true if both are the same:

const isToday = date => {
  const today = new Date()
  return date.getDate() === today.getDate() && 
      date.getMonth() === today.getMonth() && 
      date.getFullYear() === today.getFullYear()

Here is how you can use it:

const date = new Date(2022, 7, 7)
console.log(isToday(date)) // true

Alternatively, you can extend the date object by adding the above function directly to object prototype like below:

Date.prototype.isToday = function () {
  const today = new Date()
  return this.getDate() === today.getDate() && 
      this.getMonth() === today.getMonth() && 
      this.getFullYear() === today.getFullYear()

Now just call the isToday() method on any date object to compare it with today's date:

const date = new Date(2022, 7, 7)

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.