moment / luxon

⏱ A library for working with dates and times in JS
https://moment.github.io/luxon
MIT License
15.23k stars 730 forks source link

what format should I use to parse Chinese datetime 2023年6月06日 GMT-4 02:58:10 #1444

Open bodycombathuang opened 1 year ago

bodycombathuang commented 1 year ago

I want to use the following method to parse The Chinese datetime, what format should I used here, is there other way to convert 2023年6月06日 GMT-4 02:58:10 to Date variable

DateTime.fromFormat("2023年6月06日 GMT-4 02:58:10", '???', { locale: "zh-CN"})

diesieben07 commented 1 year ago

It looks like Luxon's timezone parsing tokens currently cannot handle GMT-X-type zones. I will look into what exactly needs fixing there and how to fix it. To address your specific format, you can use yyyy年MMMM月d日 'GMT'Z H:m:s as the parsing format:

const dateTime = DateTime.fromFormat('2023年6月06日 GMT-4 02:58:10', "yyyy年MMMM月d日 'GMT'Z H:m:s", {setZone: true, locale: 'zh-CN'});
console.log(dateTime.toISO()); // 2023-06-06T02:58:10.000-04:00
bodycombathuang commented 1 year ago

hi @diesieben07 , what format can be used to parse Jun 08, 2023, 03:45:15 AM EDT in English locale?

diesieben07 commented 1 year ago

That format cannot be parsed, because Luxon has no way to parse time zone names such as "EDT". The only way to parse an actual time zone (not just an offset) is to use the parsing token z, which parses an IANA zone name, such as America/New_York. The reason for this is that there is no browser / JavaScript API to parse them, and even if there was, it would be ambiguous ("EDT" for example refers to both Eastern Daylight Time as well as Australian Eastern Daylight Time).

Parsing such "natural" date formats is difficult at best and usually error prone. I would suggest using ISO 8601 instead.