Author -  Sai gowtham

Comparing the two dates in JavaScript

In this tutorial, we are going to learn about how to compare two dates in JavaScript with the help of examples.

In JavaScript, we have a new Date() constructor which returns a date object that contains different types of methods like.

  1. getDate() : Which returns the day of a month according to the specified local time.

  2. getMonth(): Which returns the month.

  3. getFullYear(): Which returns the year.

By using the above three methods we can compare two dates in JavaScript.

Here is an example:

function compareTwoDates(first,second){
                        // 17-12-2019
   const firstDate =  `${first.getDate()}-${first.getMonth()}
                       -${first.getFullYear()}`;

   const secondDate = `${second.getDate()}-${second.getMonth()}
                      -${second.getFullYear()}`

   return firstDate === secondDate
}

console.log(compareTwoDates(new Date(),new Date())); // true

In the above example, first we are constructing the dates with delimiter - then we are comparing the first date with second date, if both dates are equal it returns true else it returns false if it is not equal.

Second way using toDateString() method

Similarly, we can also compare two dates by using the toDateString() method which returns the date in English format "Mon Dec 16 2019".

const firstDate  = new Date();
const secondDate = new Date();

console.log(firstDate.toDateString() === secondDate.toDateString())

// true

Note: In the above two examples, we are not using the time to compare two dates.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY