Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment format the time will become invalid date without debug mode on React Native

moment version is 2.24.0

My date value is 2019-04-23 03:16:00 +0000 UTC

I use moment to let it become to Asia time just like:

const moment = require('moment');

const localTime = moment(date).format('YYYY/MM/DD HH:mm');

<Text>{localTime}</Text>

localTime will show 2019/04/23 11:16

It works when I test it on debug mode.

But when I close the debug mode localTime will be

invalid date

The issue happen both of Android and IOS.

Any ideas ?

like image 403
Morton Avatar asked Apr 23 '19 03:04

Morton


1 Answers

For anyone else experiencing date/time issues with Moment on Android especially if you're moving from React Native 0.59 (or older) to 0.60+, it appears that Hermes changes the way the Android works with Moment/dates. However, it would work when the debugger was enabled. Turns out, when you run the debugger, it switches back to the Chromium engine (or V8?) from Hermes. Resulted in us having to use console logs to track down Moment parsing issues. Oddly, the issues also occurred when trying the same manipulations in Safari.

If you're parsing dates passed in via different vars for day, month, year and the day or month does not have preceding zeroes (ex: 01 vs 1) then I recommend doing this: const momentFormat = { y: birthYear, m: birthMonth, d: birthDay }; return Moment(momentFormat).format('MMMM Do, YYYY'); This manually sets the values rather than relying on each value being correctly formatted or having to write custom code to ensure the day/month values have the 0 when needed.

like image 175
Brian Nash Avatar answered Oct 04 '22 03:10

Brian Nash