I have a Text
tag in expo/react-native
which i use on a screen to show live time using JavaScript new Date()
object. Its giving me 24 hour format even when i set "en-US"
and hour12: true
i have tried everything but it doesn’t seem to work.
Here is my code:
const [liveTime, setLiveTime] = useState(new Date())
const refreshLiveTime = () => {
setLiveTime(new Date())
}
useEffect(() => {
const timerId = setInterval(refreshLiveTime, 1000)
return function cleanup() {
clearInterval(timerId)
}
}, [])
And here is how i render it in Text
tag:
<Text>{liveTime.toLocaleTimeString("en-US", {hour12: true})}</Text>
Sample Expected output:
01:12:18
Output i am receiving:
13:12:18
EDIT:
I tried the same code in reactjs
and it works fine there, i think the problem is with react-native
here, maybe react-native doesn’t support toLocaleTimeString()
3
Answers
Fixed it with
moment
npm package.Where
liveTime
isnew Date()
I’m using moment, try my example:
Format date with locales is not supported by Expo or React Native by default on Android.
In case you are using bare React Native, you can add JavaScriptCore Flavors to Android to enable Internationalization API.
in
android/app/build.gradle
enable this lineNote: Enabling internationalization on android will add an extra 2MB to your app APK. Review whether it is worth it.