【问题标题】:Date formatting in React NativeReact Native 中的日期格式
【发布时间】:2020-04-06 04:44:24
【问题描述】:

我尝试根据设备设置格式化日期时间值。 无论我在模拟器设置或 xCode 方案中进行什么更改,我总是使用date.toLocaleDateString() 获得美国格式

所以我尝试了不同的库(moment、react-native-localize、...),但都一样,总是得到美国格式。

所以我尝试用这段代码直接设置语言环境:

  const date = new Date(Date.UTC(2019, 11, 26, 14, 5, 0))
  const options = {
     dateStyle: 'medium',
     timeStyle: 'short',
  }
  console.log(date.toLocaleDateString('en-US', options))               // Dec 26, 2019, 3:05 PM
  console.log(date.toLocaleDateString('fr-FR', options))               // Dec 26, 2019, 3:05 PM
  console.log(new Intl.DateTimeFormat('en-US', options).format(date))  // Dec 26, 2019, 3:05 PM
  console.log(new Intl.DateTimeFormat('fr-FR', options).format(date))  // Dec 26, 2019, 3:05 PM

我仍然得到相同的结果!

除了“en-US”之外,我可以怎样做才能在其他语言环境中显示我的日期?

我不想自己硬核格式(“DD/MM/YYY HH:mm”),我想使用我设置的区域设置或更好的设备设置。

感谢您的建议

【问题讨论】:

  • toLocaleDateString 只能在 react-native 的调试模式下工作
  • 在这个问题stackoverflow.com/questions/51769039/… 中查看 Itsik Mauyhas 的答案......你需要什么才能让它工作......

标签: android ios react-native datetime ecmascript-6


【解决方案1】:

我目前在"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

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

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

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

【讨论】:

    【解决方案2】:

    试试下面的代码:

    import Moment from 'moment';
    
    render(){
        Moment.locale('en');
        var dt = '2016-05-02T00:00:00';
        return(<View> {Moment(dt).format('d MMM')} </View>) //basically you can do all sorts of the formatting and others
    }
    

    这里有一个格式化示例:

    moment("12-25-1995", "MM-DD-YYYY");
    

    你可以在这里查看moment.js官方文档https://momentjs.com/docs/

    【讨论】:

    • 感谢 Matheus,但这不是我要寻找的。我不想将格式强制为“d MMM”或其他格式,我希望它根据电话语言显示,例如法语的“dd/mm/yyyy”或美国的“mm-dd-yyyy” .用 swift 很容易做到,但我被 React Native 困住了。
    • 此外,该示例适用于英语,但不适用于“fr”。
    • 这正是问题所在,输出应该是“13/12/19”,第一天,而不是“12/13/19”。不考虑区域设置,无论您键入什么,都会得到相同的结果!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2022-06-27
    • 2018-08-07
    • 1970-01-01
    • 2017-10-05
    • 2021-12-06
    • 2018-10-23
    相关资源
    最近更新 更多