What's the main difference between:
dt = new Date();
ms = Date.parse(dt);
and
dt = new Date();
ms = dt.getTime();
they have the same output, but what the difference? and which one should i use?
Date.prototype.getTime() The getTime() method returns the number of milliseconds since the ECMAScript epoch. You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method.
Date.parse() The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970. We can get the timestamp with the getTime() method.
Though it's an old post, I'll leave my answer for someone who visit here later than me.
dt = new Date();
// often false, occasionally true
Date.parse(dt) === dt.getTime()
This is because you will lose the information about milliseconds when you do dt.toString()
which is internally called by Date.parse(dt)
. At least for Chrome (63.0.3239.84) and Firfox Quantum (57.0.3), they implement the toString()
method of Date object like this way. You can try the following example yourself.
dt = new Date('2018.1.1 01:01:01.001')
dt.getTime() // 1514739661001
Date.parse(dt) // 1514739661000
Date.parse(dt)
equals to dt.getTime()
only if dt
is captured at the moment that millisecond equals 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With