Comparing the two dates in JavaScript
In this post we will give you information about Comparing the two dates in JavaScript. Hear we will give you detail about Comparing the two dates in JavaScriptAnd how to use it also give you demo for it if it is necessary.
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.
-
getDate() : Which returns the day of a month according to the specified local time.
-
getMonth(): Which returns the month.
-
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.
Hope this code and post will helped you for implement Comparing the two dates in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs