moment-timezone icon indicating copy to clipboard operation
moment-timezone copied to clipboard

moment time string parsing defect with timezone

Open skang opened this issue 4 years ago • 4 comments

Moment-timezone version which you use:

Version: 0.5.32

Issue description: when constructing a moment object from a date time string with one digit hour format, the parsing algorithm seems to be defective. This defect does not show up when using two-digit hour format. Please see example code below:

moment.tz("2021-01-23 0:02", moment.tz.guess()).format('YYYY-MM-DD HH:mm') result: "2021-01-22 19:02" (DEFECTIVE)

moment.tz("2021-01-23 00:02", moment.tz.guess()).format('YYYY-MM-DD HH:mm') result: "2021-01-23 00:02" (CORRECT)

skang avatar Jan 23 '21 05:01 skang

A single-digit year is not part of Moment's default parsing formats, so it will fall back to using new Date(input). This has very inconsistent results across browsers, which is why the Moment parsing guide says:

If you know the format of the date string that you will be parsing, it is always the best choice to explicitly specify that format.

This code should work to get consistent results:

moment.tz("2021-01-23 0:02", "YYYY-MM-DD H:mm", moment.tz.guess())

gilmoreorless avatar Jan 23 '21 21:01 gilmoreorless

Please read the description and example carefully - It is NOT a "single-digit year" problem, it is a "single-digit hour" problem. Thanks

skang avatar Jan 25 '21 06:01 skang

Hi, gilmoreorless, your solution does work :) So I guess you probably made a typo. Thank you very much for looking into the problem and provide a solution.

By the way, this problem does not occur with "moment.js" library. I wonder why it does not work with "moment-timezone".

skang avatar Jan 25 '21 06:01 skang

@skang Yep, I completely made a typo, sorry for the confusion!

gilmoreorless avatar Jan 25 '21 10:01 gilmoreorless