JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to check if date is greater than another date in JavaScript?

To check if a date is greater than another date, compare two Date objects, date1 > date2. If date1 is greater, the comparison will return true; otherwise, it will return false.

let date1  = new Date(2022, 10, 23); //23 November 2022
let date2 = new Date(2022, 0, 27); //27 January 2022

if(date1 > date2){
  console.log("date1 is greater than date2.");
  console.log("date1 is equal to or less than date2.");


date1 is greater than date2.

Explanation of the code:

1 A date object is created by calling the Date() constructor and passing year, month, date, hours, minutes and seconds.

let d = new Date(2022, 9, 2, 19, 1, 0);
console.log(d); //"Sun Oct 02 2022 19:01:00 GMT+0530 (India Standard Time)"

Date class follows zero-based numbering for month. This means January is 0 not 1, February is 1, March is 2, and so on.

2 When you compare two Date objects, each Date object is converted to its timestamp value. The timestamp is the number of milliseconds between 1 January 1970 and a given date. You can get that millisecond value by calling the getTime() method.

let d = new Date(2022, 9, 2);
console.log(d); //"Sun Oct 02 2022 00:00:00 GMT+0530 (India Standard Time)"
console.log(d.getTime()); //1664649000000

Recommended Posts