How to compare two dates in JavaScript

Asked 1 years ago, Updated 1 years ago, 132 views

I'd like to compare the two dates using JavaScript. I don't know what to do. Can someone explain it to me?

javascript date datetime

2022-09-22 22:09

1 Answers

If you use a Date object, you can do most of what you want. When you create each object, you can use operators such as >, <, <=, >=.

Use date.getTime() to write operators such as ==, !=, ===, and !==. For example,

var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();

Like this.

I think it would be good to look at the examples below and study the difference.

var d1 = new Date();
var d2 = new Date(d1);

console.log(d1 == d2);   // prints false (wrong!) 
console.log(d1 === d2);  // prints false (wrong!)
console.log(d1 != d2);   // prints true  (wrong!)
console.log(d1 !== d2);  // prints true  (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)


2022-09-22 22:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.