svaarala / duktape

Duktape - embeddable Javascript engine with a focus on portability and compact footprint
MIT License
5.97k stars 515 forks source link

Parsing dates in non-ISO format #1984

Open jcmerlin opened 6 years ago

jcmerlin commented 6 years ago

I have code that does this:

var d = new Date('9/8/18');
// Do something with d.

However, Duktape cannot parse this date correctly and creates an invalid Date object.

I saw this issue: https://github.com/svaarala/duktape/issues/712 but I don't know what's the current status of it. Is it implemented, at least on Unix platforms? What'd be the best way to have this feature at least only for Unix platforms? Thanks

svaarala commented 6 years ago

You can provide a custom Date parser via DUK_USE_DATE_PARSE_STRING. See https://github.com/svaarala/duktape/blob/master/doc/datetime.rst#external-date-providers.

svaarala commented 6 years ago

As for what's the best parser for parsing a wide variety of different formats, I don't have a recommendation for that. For Unix platforms Duktape automatically uses strptime() with %c:

       %c     The date and time representation for the current locale.

This works e.g. with:

duk> new Date('Sun Sep 23 17:27:23 2018')
= "2018-09-23T14:27:23.000Z"

But it comes down to the locale settings and strftime/strptime in the platform.

jcmerlin commented 6 years ago

Thanks.

svaarala commented 6 years ago

If you end up with a good solution which accepts a wide range of Date formats, it'd be nice to hear :)

svaarala commented 6 years ago

@jcmerlin Any update on this issue?

mxmauro commented 6 years ago

You can run/embed moment.js. Works fine.

svaarala commented 6 years ago

Yeah, that's true - but it may not be a possible solution if the Date built-in specifically has to accept the locale specific formats (e.g. if you have an existing code base you don't control).