为什么toLocaleDateString无法在react-native(Android)中工作?

S.j*_*kib 6 javascript date react-native

由于某些奇怪的原因,toLocaleDateStringreact-native无法正常工作。有时它起作用,有时却不起作用。对于以下代码,

const dateString = this.state.date.toLocaleDateString('en-US', {
            weekday: 'short',
            day: 'numeric',
            month: 'long',
            year: 'numeric',
        });
Run Code Online (Sandbox Code Playgroud)

有时我得到公正的07/17/2018输出,有时得到正常的输出。现在,我可以自己实现它,也可以使用moment.js类似的东西。我想知道为什么会这样。

ver*_*nar 9

我目前"react-native": "~0.63.3",在使用 toLocaleDateString 时遇到同样的问题。这是为我解决的问题:

在我的 android/app/build.gradle 文件中,我替换了以下行

def jscFlavor = 'org.webkit:android-jsc:+' //remove this - it might be something else depending on your react-native version, try to look in your build.gradle file for similar comment I posted below in the picture
Run Code Online (Sandbox Code Playgroud)

def jscFlavor = 'org.webkit:android-jsc-intl:+' // add this
Run Code Online (Sandbox Code Playgroud)

在这里找到解决方案:https ://github.com/react-community/jsc-android-buildscripts#international-variant

在我的 build.gradle 文件中,有一条来自 react-native 的评论,描述了该问题

在此输入图像描述


SDu*_*han 7

React Native在非调试模式下使用JavaScriptCore引擎,它不能很好地与日期配合使用,但是在调试期间可以工作,因为它在调试时使用chrome V8引擎。

因此,最好使用momentXDate JavaScript库。