1

Given the following standardized date string:

var dateString = "2010-12-23T23:12:00";

I can use one of the following snippets of code to parse it:

Example 1:

var date = new Date(dateString);

Example 2:

var date = new Date(Date.parse(dateString));

According to this answer, date parsing is only well-defined when the string is of the format YYYY-MM-DDTHH:mm:ss.sssZ. If the string is in that format, however, I would imagine that the two examples would always return the exact same result.

What are the technical differences between these two approaches to creating a date object from a standardized date string, and do they ever return different results?

Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78

1 Answers1

1

I ended up finding the answer to this question shortly after I wrote it. According to the ECMAScript Language Specification, for a string argument these two approaches will yield identical results in standards-compliant browsers.

From the ECMAScript Language Specification:

15.9.3.2 new Date(value):

  1. Call ToPrimitive(value).

  2. If Type(Result(1)) is String, then go to step 5.

...

  1. Parse Result(1) as a date, in exactly the same manner as for the parse method (15.9.4.2); let V be the time value for this date.

When new Date(string) is called, it parses the string in the exact same way as Date.parse(string) would. So by calling new Date(Date.parse(string)) we get the exact same result as new Date(string), but at the performance cost of an extra method call.

Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78