Sitemap
Pravin M

Pravin M

I am a frontend developer with 10+ years of experience Blog :- https://www.frontendinterviewquestions.com

Member-only story

Compare two dates in JavaScript

3 min readAug 4, 2024

--

Press enter or click to view image in full size
Compare two dates in JavaScript

For more questions and answers visit our website at Frontend Interview Questions

Understanding JavaScript Date Object

In JavaScript, dates are handled using the Date object, which allows you to create, manipulate, and format dates.

Creating a Date Object:

let date1 = new Date('2024-01-01');
let date2 = new Date('2024-12-31');
console.log(date1); // Outputs: Mon Jan 01 2024 00:00:00 GMT+0000 (Coordinated Universal Time)
console.log(date2); // Outputs: Tue Dec 31 2024 00:00:00 GMT+0000 (Coordinated Universal Time)

Methods to Compare Dates

There are several ways to compare dates in JavaScript. The most common methods involve comparing the time values of the dates.

  1. Using getTime() Method

The getTime() method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. Comparing these time values provides a straightforward way to determine the relationship between two dates.

Example:

let date1 = new Date('2024-01-01');
let date2 = new Date('2024-12-31');
if (date1.getTime() > date2.getTime()) {
console.log('date1 is after date2');
} else if (date1.getTime() < date2.getTime()) {
console.log('date1 is before…

--

--

Pravin M
Pravin M

Written by Pravin M

I am a frontend developer with 10+ years of experience Blog :- https://www.frontendinterviewquestions.com