JS Example for Beginners: JavaScript Program to Compare The Value of Two Dates

(JavaScript programming Example for Beginners)

JavaScript Program to Compare The Value of Two Dates

In this example, you will learn to write a JavaScript program that will compare the values of two dates.


Example: Compare Value of Two Dates

// program to compare value of two dates
// create two dates
let d1 = new Date();
let d2 = new Date();

// comparisons
let compare1 = d1 < d2;

let compare2 = d1 > d2;

let compare3 = d1 <= d2;

let compare4 = d1 >= d2;

let compare5 = d1.getTime() === d2.getTime();

let compare6 = d1.getTime() !== d2.getTime();



In the above example, the new Date() constructor is used to create a date object.

The new Date() gives the current date and time.

let d1 = new Date();
console.log(time); // Fri Aug 28 2020 09:19:40 GMT+0545 (+0545)

You can then directly compare these two dates using comparisons ><<=, or >=.

However, to use comparisons like ==!====, or !==, you have to use date.getTime().

The getTime() method returns the number of milliseconds from midnight of January 1, 1970 (EcmaScript epoch) to the specified date.

let d1 = new Date().getTime();
console.log(d1); // 1598585951699


JS Example for Beginners: JavaScript Program to Compare The Value of Two Dates

Sign up to get end-to-end “Learn By Coding” example.

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.