简体   繁体   English

在javascript中以本地日期格式解析Datetime字符串(最好使用luxon)

[英]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 . 假设我有一个日期时间字符串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. 现在,如果我在美国,我将其读为2019年10月9日;如果我在印度,我将其读为2019年9月10日。

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. 因此,我的问题是如何以基于本地时区的方式解析此字符串作为Date对象。

I am using luxon , but, pure javascript solution will also work. 我正在使用luxon ,但是纯JavaScript解决方案也可以使用。

Using a recent version of Luxon that supports the use of "macro" tokens in the parser: 使用支持在解析器中使用“宏”令牌的最新版本的Luxon:

> 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. IMO,此解决方案很脆弱,因为Luxon的解析器在这里非常严格,本质上要求日期部分在该语言环境中与DateTime.toFormat 完全匹配,因此0填充,斜杠与连字符之间的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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