Javascript Dates: Comparing and Testing for Equality

JavaScript provides various ways to compare and test dates, but it's crucial to understand the underlying differences to avoid unexpected results
Example 1: Comparing Dates using getTime()

 
const date1 = new Date('2023-12-18');
 
const date2 = new Date('2023-12-17');
 
const areDatesEqual = date1.getTime() === date2.getTime();
 
 
console.log(areDatesEqual); // Output: false
 
 

Explanation:

  • This example creates two date objects: date1 for today (2023-12-18) and date2 for yesterday (2023-12-17).
  • We use the getTime() method to get the number of milliseconds since 1970-01-01T00:00:00Z for each date.
  • Using strict comparison (===), we check if the timestamps are equal. Since it's not the same day, the output is false.

 

Comparing Date parts using specific methods

 
const date1 = new Date("2023-12-18"); // December 18, 2023 const
 date2 = new Date("2023-12-18"); // December 18, 2023 const
 date3 = new Date("2023-12-19"); // December 19, 2023 
 
console.log(date1.getFullYear() === date2.getFullYear()); 
// Output: true 
console.log(date1.getMonth() === date2.getMonth());
 // Output: true 
console.log(date1.getDate() === date3.getDate());
 // Output: false 
console.log(date1.toDateString() === date2.toDateString()); 
// Output: true 
console.log(date1.toDateString() === date3.toDateString()); 
// Output: false 
 
 

Explanation: Date objects offer methods like getFullYear(), getMonth(), and getDate() to extract specific date components. Comparing these values individually allows you to check only for year, month, or day equality. Additionally, toDateString() returns a formatted string representation of the date, enabling comparison based on the complete date format.

Using Comparison Operators:

 
const today = new Date();
const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
// Subtract 1 day in milliseconds
 
const isTodayEqualYesterday = today === yesterday;
// False
const isTodayAfterYesterday = today > yesterday;
// True
 
console.log("Today = Yesterday:", isTodayEqualYesterday);
console.log("Today > Yesterday:", isTodayAfterYesterday);
 

Explanation:

  • We create today and yesterday dates using new Date().
  • getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
  • We subtract 24 hours from today in milliseconds to get yesterday.
  • today === yesterday returns false because Date objects are compared by reference, not value.
  • today > yesterday returns true because we compared the timestamps.