We could parse this previously on JSC using
new Date() but for some reason it results in an
"Invalid Date" on Hermes. Turns out the problem was in the time zone offset. Hermes could only parse ISO dates containing a time zone offset in
but not in a format without a colon
So until this gets fixed in Hermes we will need to implement a workaround. We used the custom date formatter from Day.js – a great library which we were already making use of in our codebase.
Day.js depends on
new Date() for parsing under the hood. Meaning it would still fail to parse our date when running Hermes. A small bundle size is one of the main features of Day.js so the package ships with only core functionality. To extend its capabilities, we use plugins. And the one we need is CustomParseFormat:
import dayjs from "dayjs" import customParseFormat from "dayjs/plugin/customParseFormat" dayjs.extend(customParseFormat)
That's it! Quite straightforward.
Now we just need to define our format. To give Dayjs the ability to parse our date, we need to tell it what our date looks like based on these defined formats, e.g.:
||1-12||The month, beginning at 1|
||01-12||The month, 2-digits|
||1-31||The day of the month|
||01-31||The day of the month, 2-digits|
||00-23||The hour, 2-digits|
||00-59||The minute, 2-digits|
||00-59||The second, 2-digits|
||000-999||The millisecond, 3-digits|
||+05:00||The offset from UTC, ±HH:mm|
||+0500||The offset from UTC, ±HHmm|
You can find the full reference here.
Our date looks like
2021-08-31T17:00:00.000+0300, so the format we need would be:
'T' here is a constant which would be present in the expected date string YYYY-MM-DDTHH:mm:ss.SSSZZ
Using our custom format:
dayjs("2021-08-31T17:00:00.000+0300", "YYYY-MM-DDTHH:mm:ss.SSSZZ").toISOString() // 2021-08-31T14:00:00.000Z
That works! And once the fix for Hermes is in, we can replace it with a regular JS date constructor call.
Check out the source code for CustomParseFormat.
This article was cross-posted from my personal blog. Do subscribe to me there!