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

  1. SDK Version: 16
  2. Platforms(Android/iOS/web/all): Android

I have a Text tag in a screen, which i use 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()

Hi @nasyxrakeeb

This all depends on the JavaScript engine that is in use. Let’s assume you’re using Chrome for the reactjs test. In that case you’re using the Chrome JavaScript engine. If you were using another browser you could potentially get different results.

Parameters

The locales and options arguments customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the Intl.DateTimeFormat API, these parameters correspond exactly to the Intl.DateTimeFormat() constructor’s parameters. Implementations without Intl.DateTimeFormat support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.

In React Native, the usual JavaScript engine is JavaScriptCore. If you search for something like:

javascriptcore "toLocaleTimeString"

you will find many links talking about this issue. e.g.:

These days there is another JavaScript engine that’s becoming popular on React Native called Hermes. I haven’t tried your code on Hermes, but the following page suggests that it might work for you:

See the docs for how to switch to Hermes:

toLocaleTimeString isn’t part of the core js library used in react-native for android. No idea why, it is for ios. I ended up using momentJs for this (and a few other) reasons to handle the localization.