Program JavaScript untuk Membandingkan Nilai Dua Tanggal

Contoh: Bandingkan Nilai Dua Tanggal

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

// comparisons
const compare1 = d1 < d2;
console.log(compare1);

const compare2 = d1 > d2;
console.log(compare2);

const compare3 = d1 <= d2;
console.log(compare3);

const compare4 = d1 >= d2;
console.log(compare4);

const compare5 = d1.getTime() === d2.getTime();
console.log(compare5);

const compare6 = d1.getTime() !== d2.getTime();
console.log(compare6);

Keluaran

false
false
true
true
true
false

Dalam contoh di atas, new Date() konstruktor digunakan untuk membuat objek tanggal.

Itu new Date() memberikan tanggal dan waktu saat ini.

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

Anda kemudian dapat langsung membandingkan dua tanggal ini menggunakan operator perbandingan >, <, <=, atau >=.

Namun, untuk menggunakan operator perbandingan seperti ==, !=, ===, atau !==, Anda harus menggunakan date.getTime().

Itu getTime() metode mengembalikan jumlah milidetik dari tengah malam 1 Januari 1970 (EcmaScript zaman) ke tanggal yang ditentukan.

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