简体   繁体   中英

toLocaleTimeString doesn't convert time to 12 hour format in react native

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()

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 line


def jscFlavor = 'org.webkit:android-jsc-intl:+' 

Note: Enabling internationalization on android will add an extra 2MB to your app APK. Review whether it is worth it.

I'm using moment , try my example :

import moment from 'moment';

const time = new Date();
console.log(moment(time).format("hh:mm:ss"));
// if you want display by 24h, change hh:mm:ss to HH:mm:ss

Fixed it with moment npm package.

moment(liveTime, "HH:mm:ss").format("hh:mm:ss A")

Where liveTime is new Date()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM