Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Date.parse() and .getTime()

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?

like image 463
faid Avatar asked Sep 21 '13 18:09

faid


People also ask

What does date getTime () do?

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.

What is date parse?

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).

Where does JavaScript get time from?

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.


1 Answers

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.

like image 149
momocow Avatar answered Sep 19 '22 11:09

momocow