<Text style={s.date}>{ new Date(this.props.order.ordered_at).toLocaleDateString('en-US', { day: '2-digit', month: 'short' }) }</Text>
<Text style={s.time}>({ new Date(this.props.order.ordered_at).toLocaleTimeString('en-US', { hour: '2-digit', minute:'2-digit', hour12: true }) })</Text>
Output when JS remote debugging is off
02/13/17 (23:51:31)
02/13/17 (23:48:07)
Output when JS remote debugging is on
Feb 13 (11:51 PM)
Feb 13 (11:48 PM)
What's causing this and how do I fix it?
import moment from 'moment';
<Text style={s.date}>{ moment(new Date(this.props.order.ordered_at)).format('ll') }</Text>
<Text style={s.time}>{ moment(new Date(this.props.order.ordered_at)).format('LT') }</Text>
will consistently yield
Feb 13, 2017 (11:51 PM)
Feb 13, 2017 (11:48 PM)
Why doesn't the usual Date()
way work?
JavaScript Runtime When using React Native, you're going to be running your JavaScript code in two environments:
- On iOS simulators and devices, Android emulators and devices React Native uses JavaScriptCore which is the JavaScript engine that powers Safari. On iOS JSC doesn't use JIT due to the absence of writable executable memory in iOS apps.
- When using Chrome debugging, it runs all the JavaScript code within Chrome itself and communicates with native code via WebSocket. So you are using V8.
While both environments are very similar, you may end up hitting some inconsistencies. We're likely going to experiment with other JS engines in the future, so it's best to avoid relying on specifics of any runtime.
So, as mentioned in the comments, it's better to use momentJS
instead of relying blindly on the JS of the environment doing which can lead to inconsistencies as mentioned in the docs
I was facing the same problem till I started to use the following code:
moment(`${post.date}+02:00`).
Here I had used +02:00
since the server date is in GMT+2 timezone. You should change it to adjust your server date timezone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With