最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Jul 2, 2019 at 14:28 Pointy 414k62 gold badges594 silver badges626 bronze badges asked Jul 2, 2019 at 14:26 Ankit KanteAnkit Kante 2,1393 gold badges21 silver badges41 bronze badges 4
  • 1 What you're describing isn't really related to timezones; it's date format preference based on culture, day/month/year vs month/day/year. If you want that handled properly, you'll likely have to allow your users to set their date format preference, but hopefully for display only. Most systems expect dates/timestamps to be handled in year-month-day hour:minute:second, with or without timezone (+/- offset) included. – Tim Lewis Commented Jul 2, 2019 at 14:33
  • Did you read the luxon documentation? moment.github.io/luxon/docs/manual/parsing.html#fromformat – user47589 Commented Jul 2, 2019 at 14:33
  • fromFormat expects a format to be provided. I want automatic parsing based on culture. I guess as Tim suggested, I need to switch to year-month-day hour:minute:second – Ankit Kante Commented Jul 2, 2019 at 14:55
  • 3 So your real question is "how do I tell what format the user expects". You can't, so present timestamps in an unambiguous format, and tell the user the format you expect when requesting input. – RobG Commented Jul 2, 2019 at 20:18
Add a comment  | 

1 Answer 1

Reset to default 14

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.

发布评论

评论列表(0)

  1. 暂无评论