Javascript Date Compare via valueOf()

Description

Javascript Date Compare via valueOf()


let Halloween = new Date("Oct 31, 2009");
let AprilFools = new Date("Apr 1, 2009");

console.log(Halloween > AprilFools);  // true

// Create two dates that are exactly the same
Halloween = new Date("Oct 31, 2009 UTC");
let Holloween2 = new Date(Halloween.valueOf());

// Write out the dates to ensure they are the same
console.log("Holloween: " + Halloween.toString() + ", Halloween2: " + Holloween2.toString());
// For me: Holloween: Fri Oct 30 2009 17:00:00 GMT-0700 (PDT), Halloween2: Fri Oct 30 2009 17:00:00 GMT-0700 (PDT)

// This will fail.. you cannot test this way
console.log(Halloween == Holloween2);  // false

// compare the primitive value instead of the object reference
console.log(Halloween.valueOf() == Halloween2.valueOf());    // true



PreviousNext

Related