简体   繁体   English

为什么 toLocaleDateString 不能在 react-native (Android) 中工作?

[英]Why isn't toLocaleDateString working in react-native (Android)?

For some strange reasons, toLocaleDateString isn't working properly in react-native.由于一些奇怪的原因, toLocaleDateString在 react-native 中无法正常工作。 Sometimes it works, sometimes it doesn't.有时有效,有时无效。 For the following code,对于以下代码,

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

Sometimes I get just 07/17/2018 and sometimes regular output.有时我只得到 2018 年 7 月 17 日,有时是常规的07/17/2018 Now I can implement it myself or use moment.js or something like that.现在我可以自己实现它或使用moment.js或类似的东西。 I want to know why this is behaving like that.我想知道为什么会这样。

React Native used JavaScriptCore engine in non-debug mode & it doesn't work well with dates, but work during debug because it use chrome V8 engine while debugging. React Native 在非调试模式下使用 JavaScriptCore 引擎,它不能很好地处理日期,但在调试期间工作,因为它在调试时使用 chrome V8 引擎。

So it is better to use moment or XDate JavaScript library.所以最好使用momentXDate JavaScript 库。

SDushan is right. SDushan是对的。 It is better to use either Moment or XDate.最好使用 Moment 或 XDate。

But I chose to write a small function instead of importing the whole library.但是我选择写一个小函数而不是导入整个库。

function getDateString(date) {
    if (Platform.OS === 'ios')
        return date.toLocaleDateString('en-US', {
            weekday: 'short',
            day: 'numeric',
            month: 'long',
            year: 'numeric',
        });
    else {

        var
            dayOfWeek = ["Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"],
            monthName = ["January", "February", "March", "April", "May", "June",
                         "July", "August", "September", "October", "November", "December"],
            utc = date.getTime() + date.getTimezoneOffset() * 60000,
            US_time = utc + (3600000 * -4),
            US_date = new Date(US_time);

        return dayOfWeek[US_date.getDay()-1] + ", " + monthName[US_date.getMonth()] +
               " " + US_date.getDate() + ", " + US_date.getFullYear();
    }
}

I used moment like SDushan said, here is an example:我使用了像Sdushan所说的 moment,这是一个例子:

import i18n from '../i18n';

const moment = require('moment');

moment.locale('es', {
  months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),
  weekdays : 'domingo_lunes_martes_miercoles_jueves_viernes_sábado'.split('_'),
  relativeTime : {
      future : 'dentro de %s',
      past : 'hace %s',
      s : 'algunos segundos',
      m : 'un minuto',
      mm : '%d minutos',
      h : 'una hora',
      hh : '%d horas',
      d : 'un día',
      dd : '%d días',
      M : 'un mes',
      MM : '%d meses',
      y : 'un año',
      yy : '%d años'
  }
});

export const translateDate = date => {
    const currentLanguage = i18n.language;
    moment.locale(currentLanguage); // or moment.locale('es')
    const dateString = moment(date).format('dddd Do MMMM, YYYY');
    return dateString.charAt(0).toUpperCase() + dateString.slice(1)
}

Then you can use it in your component:然后你可以在你的组件中使用它:

<View style={Styles().containerDate}>
     <Input
          inputContainerStyle={Styles().inputContainerStyle}
          inputStyle={Styles().inputText}
          editable={false}
          label={i18n.t(`${i18nConfinement}.startdate`)}
          placeholderTextColor={Styles().placeholder.color}
          value={translateDate(startDate)}
      />
      <Icon onPress={() => setShowStartDate(!showStartDate)} size={25} name={showStartDate ? 'calendar-check-o' : 'calendar'} color={Styles().icon.color} type='font-awesome' />
 </View>

Here is an article about how to manage dates using moment.js 是一篇关于如何使用 moment.js 管理日期的文章

Final result:最后结果:

在此处输入图片说明

i used it to get dd.MM.yyyy HH:mm:ss format, worked well我用它来获得 dd.MM.yyyy HH:mm:ss 格式,效果很好

 function addZero(i) { if (i < 10) { i = "0" + i; } return i; } const convertUTCToLocalTime = (dateString) => { let date = new Date(dateString); const milliseconds = Date.UTC( date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), ); const localTime = new Date(milliseconds); return localTime.getDate() + "." + localTime.getMonth() + "." + localTime.getFullYear() + " " + addZero(localTime.getHours()) + "." + addZero(localTime.getMinutes()) + "." + addZero(localTime.getSeconds()); };

I am currently on "react-native": "~0.63.3", and have the same issue when using toLocaleDateString.我目前正在使用"react-native": "~0.63.3",并且在使用 toLocaleDateString 时遇到同样的问题。 Here is what fixed it for me:这是为我解决的问题:

In my android/app/build.gradle file I replaced the following line在我的 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

with

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

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

and in my build.gradle file there is a comment from react-native, that describes that issue在我的 build.gradle 文件中有来自 react-native 的评论,描述了这个问题

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM