0

I want to parse a string date time to a JavaScript Date object. I'm wondering why using +Number in the string gives me different result from using (TimeZome)

Example:

let a = new Date('Nov 01, 2022 09:00:00 +0900')
let b = new Date('2022-11-01T09:00:00.000+09:00')
let c = new Date('01 Nov 2022 09:00:00 (JST)')
let d = new Date('Nov 01, 2022 09:00:00 (JST)')

console.log(`${a.getTime()}    ${a.toISOString()}   ${a.toLocaleString('en-us', { timeZone: 'JST' })}`);
console.log(`${b.getTime()}    ${b.toISOString()}   ${b.toLocaleString('en-us', { timeZone: 'JST' })}`);
console.log(`${c.getTime()}    ${c.toISOString()}   ${c.toLocaleString('en-us', { timeZone: 'JST' })}`);
console.log(`${d.getTime()}    ${d.toISOString()}   ${d.toLocaleString('en-us', { timeZone: 'JST' })}`);

the result is

"1667260800000    2022-11-01T00:00:00.000Z   11/1/2022, 9:00:00 AM"
"1667260800000    2022-11-01T00:00:00.000Z   11/1/2022, 9:00:00 AM"
"1667318400000    2022-11-01T16:00:00.000Z   11/2/2022, 1:00:00 AM"
"1667318400000    2022-11-01T16:00:00.000Z   11/2/2022, 1:00:00 AM"

it looks like using (JST) does not generate the correct result!

Note: I get the same result when I use Date.parse

DaNeSh
  • 1,022
  • 1
  • 14
  • 24
  • 2
    yes, the browser doesn't seem to recognize `(JST)` ---- if you're using the default date parser, you should really be providing an ISO 8601 compliant date string – skara9 Jan 28 '22 at 19:46
  • @skara9 the funny part is browser does not throw error – DaNeSh Jan 28 '22 at 19:48
  • That's pretty common in native JS methods. `parseInt` will return a valid result from `123abc`. Garbage at the end of the input is simply ignored. – D M Jan 28 '22 at 19:49
  • Please check out -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse specifically, bit like -> `This section contains implementation-specific behavior that can be inconsistent across implementations.`, IOW: Date parsing in Javascript is very limited. – Keith Jan 28 '22 at 20:06
  • 1
    @DaNeSh—where the Date constructor is called with a single string value, it's parsed as for [*Date.parse*](https://262.ecma-international.org/#sec-date.parse). The closest that algorithm gets to throwing an error is to return *NaN* if it can't parse the string to a valid [*time value*](https://262.ecma-international.org/#sec-time-values-and-time-range). If the string doesn't conform to one of the two formats supported by ECMA-262, then parsing is implementation dependent (per [the duplicate](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results)). – RobG Jan 28 '22 at 22:09

0 Answers0