Hello all javascript guru,
I’ve came across this javascript code that struggled me abit to understand why it didn’t work as expected. So thought i post it here seeking for your help.
Basically the code is to convert a Date to milliseconds format and that milliseconds value then be converted back to Date object again but when comparing, they are NOT equal?
var currentTime = new Date();
var currentTimeInMill = Date.parse(currentTime);
var currentTime2 = new Date(currentTimeInMill);
// debug in firefox
console.log(currentTime);
// Date {Thu Jul 07 2011 09:56:19 GMT+1000 (AUS Eastern Standard Time)}
console.log(currentTime2);
// Date {Thu Jul 07 2011 09:56:19 GMT+1000 (AUS Eastern Standard Time)}
console.log(currentTime == currentTime2);
// false
My question is why that 2 values currentTime and currentTime2 are not equal even their values “look” the same in Firefox console.log?
Because, as minitech points out, milliseconds are stripped from the Date object’s
toStringmethod, in order to be absolutely sure that the numeric value ofcurrentTimeequals that ofcurrentTime2, you’ll need to set the milliseconds ofcurrentTime2:Then, as cwolves points out, you can compare each
Date‘sgetTimeoutput. So when complete, it would look something like this: