moment / moment-timezone

Timezone support for moment.js
momentjs.com/timezone
MIT License
3.82k stars 835 forks source link

"Friendly" should be invalid date, but it read as valid date #1071

Closed elliotching closed 7 months ago

elliotching commented 1 year ago

Environment

For bug reports, please run the following code in your environment and include the output:

console.log({
  moment: moment.version,
  momentTz: moment.tz.version,
  date: (new Date()).toString(),
  intlZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
});

Issue description

A word "Friendly" is being false positively recognised as valid date, which should not be the case.

console.log({
    moment: moment.version,
    momentTz: moment.tz.version,
    date: (new Date()).toString(),
    intlZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  });
console.log(moment("Friendly", "ddd, MMM DD, YYYY").toString())
{
  moment: '2.29.4',
  momentTz: '0.5.43',
  date: 'Wed Jul 26 2023 14:37:50 GMT+0800 (Malaysia Time)',
  intlZone: 'Asia/Kuala_Lumpur'
}
Fri Jul 28 2023 00:00:00 GMT+0800

Expected Output

{
  moment: '2.29.4',
  momentTz: '0.5.43',
  date: 'Wed Jul 26 2023 14:37:50 GMT+0800 (Malaysia Time)',
  intlZone: 'Asia/Kuala_Lumpur'
}
"Invalid date"
sslincoco commented 1 year ago

您的邮件已收到,我会尽快给您回复。

gilmoreorless commented 1 year ago

The ddd at the start of the format string is looking for a day name. Since day names can be any string based on locale, I suspect it's treating "Friendly" as the name, then moving on to look for the other parts of the date. It doesn't find any and uses lenient fallbacks.

Trying to parse it without the format string, or with different format strings, produces the expected result:

moment("Friendly").toString();  // 'Invalid Date'
moment("Friendly", "YYYY").toString();  // 'Invalid Date'
moment("Friendly", "MMM DD, YYYY").toString();  // 'Invalid Date'