skip to Main Content

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


  1. Chosen as BEST ANSWER

    Fixed it with moment npm package.

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

    Where liveTime is new Date()


  2. 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
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search