我在
Text
中有一个 expo/react-native
标签,我在屏幕上使用它来使用 JavaScript new Date()
对象显示实时时间。即使我设置了 "en-US"
和 hour12: true
,它也给了我 24 小时格式,我已经尝试了所有方法,但似乎不起作用。
这是我的代码:
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()
Android 上的 Expo 或 React Native 默认不支持使用区域设置格式化日期。
如果您使用裸露的 React Native,您可以将 JavaScriptCore Flavors 添加到 Android 以启用国际化 API。
在
android/app/build.gradle
中启用此行
def jscFlavor = 'org.webkit:android-jsc-intl:+'
注意:在 Android 上启用国际化将为您的应用 APK 添加额外的 2MB。看看是否值得。
使用
moment
npm 包修复了它。
moment(liveTime, "HH:mm:ss").format("hh:mm:ss A")
其中
liveTime
是 new Date()
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
要每秒更新一次,您只需要对
refreshLiveTime
函数进行一些小的更改:setLiveTime(new Date())
到 setLiveTime(moment(time).format("hh:mm:ss"))
和 const [liveTime, setLiveTime] = useState("00:00:00")