2

I wonder why the next line works:

new Date("06/19/2019 06:42 EDT") //Wed Jun 19 2019 13:42:00 GMT+0300

But this one does not:

new Date("06/19/2019 06:42 CEST") //Invalid date
Chen
  • 2,958
  • 5
  • 26
  • 45
  • 4
    The date constructor expects RFC 8601 strings. Anything else is fair game whether it works. –  Aug 05 '19 at 13:46
  • 3
    see this https://stackoverflow.com/a/15494369/8353201 – Moshe Fortgang Aug 05 '19 at 13:53
  • @amy—you might have meant ISO 8601 or RFC 2822 (or RFC 3339), but the ECMAScript parseable formats aren't exactly either. Best to just refer to relevant parts of ECMA-262. ;-) – RobG Aug 06 '19 at 05:45

1 Answers1

1

Constructors for JavaScript Date objects can use any of these syntax options:

1) new Date();
2) new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
3) new Date(value);
4) new Date(dateString);


Your examples are using option #4, datestring -- regarding which, n.b.:

"Parsing of date strings with the Date constructor ... is strongly discouraged due to browser differences and inconsistencies."


If you must use the dateString option for your constructor, the string needs to be "specified in a format recognized by the Date.parse() method" (that is, either an IETF-compliant RFC 2822 timestamp or a string in a version of ISO8601).

This formatting requirement is likely where your attempt is going sideways -- but as mentioned above, results will vary by browser -- so you might consider constructing a default Date object and using the setters provided by the Date class to assign your desired values.

For example (if the timezone you want matches the timezone where your script is running):


const date = new Date();

date.setFullYear(2019);
date.setMonth(0); // Note that the months array starts with zero for January
date.setDate(1);

date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);

console.log(date.toLocaleString()); // Logs `1/1/2019, 12:00:00 AM`

Lots more information can be found on this MDN reference page.

Cat
  • 4,141
  • 2
  • 10
  • 18