简体   繁体   中英

Parse Datetime string in local date format in javascript (preferably using luxon)

Suppose I have a datetime string 10/09/2019 10:03:00.000 AM .

Now, if I am in USA, I'll read it as 9th October 2019 and if I am in India, I'll read it as 10th September 2019.

So, my question is how do I parse this string as a Date object in such a way that it is parsed based on the local timezone.

I am using luxon , but, pure javascript solution will also work.

Using a recent version of Luxon that supports the use of "macro" tokens in the parser:

> DateTime.fromFormat("10/09/2019 10:03:00.000 AM", "D hh:mm:ss.SSS a").toISO()
'2019-10-09T10:03:00.000-04:00'
> DateTime.fromFormat("10/09/2019 10:03:00.000 AM", "D hh:mm:ss.SSS a", { locale: "en-IN" }).toISO()
'2019-09-10T10:03:00.000-04:00'

IMO, this solution is brittle, in the sense that Luxon's parser here very strict, essentially requiring that the date part match exactly DateTime.toFormat in that locale, so differences in 0-padding, slashes vs hyphens, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM