Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 955
Ankit Kante Avatar asked Jul 02 '19 14:07

Ankit Kante


People also ask

How do I convert a string to a date in Luxon?

To create one from a standard string format, use DateTime.fromISO, DateTime.fromHTTP, and DateTime.fromRFC2822. To create one from a custom string format, use DateTime.fromFormat. To create one from a native JS date, use DateTime.fromJSDate.

What is Luxon date?

Luxon is a library for dealing with dates and times in JavaScript. DateTime. now().

Should I use Luxon or moment?

Luxon is a modern Javascript date/time library built by one of the Moment. js developers to address some shortcomings in the old standby for date manipulation. It shares a lot in common with Moment. js, but I recommend you reach for Luxon the next time you need to do heavy lifting on dates and times.

How do you convert a string to a date in JavaScript?

You can Convert the date value from String to Date in JavaScript using the `Date()`` class. You can also use parse, which is a static method of the Date class. You can also split the given string date into three parts representing the date, month, and year and then convert it to Date format.


1 Answers

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.

like image 116
snickersnack Avatar answered Oct 25 '22 13:10

snickersnack