toLocaleTimeString不会在react native中将时间转换为12小时格式

7gcisfzg  于 2022-11-17  发布在  React
关注(0)|答案(3)|浏览(157)

我在expo/react-native中有一个Text标签,我在屏幕上使用JavaScript new Date()对象显示实时时间。它给了我24小时格式,即使我设置了"en-US"hour12: true,我已经尝试了所有方法,但似乎不起作用。
下面是我的代码:

const [liveTime, setLiveTime] = useState(new Date())

const refreshLiveTime = () => {
    setLiveTime(new Date())
  }

useEffect(() => {
    const timerId = setInterval(refreshLiveTime, 1000)
    return function cleanup() {
      clearInterval(timerId)
    }
}, [])

这里是我如何渲染它在Text标签:

<Text>{liveTime.toLocaleTimeString("en-US", {hour12: true})}</Text>

示例预期输出:

01:12:18

我正在接收的输出:

13:12:18

编辑:

我在reactjs中尝试了相同的代码,它在那里工作得很好,我认为问题出在这里的react-native,可能react-native不支持toLocaleTimeString()

uelo1irk

uelo1irk1#

默认情况下,Android上的Expo或React Native不支持带区域设置的日期格式。
如果您使用的是纯React Native,则可以将JavaScriptCore Flavors添加到Android以启用国际化API。
android/app/build.gradle中,使能此行

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

注意:在android上启用国际化将额外增加2MB到您的应用APK。请检查是否值得。

up9lanfz

up9lanfz2#

我正在使用moment,请尝试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
2uluyalo

2uluyalo3#

moment npm包修复了它。

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

其中liveTime等于new Date()

相关问题