如何在ReactNative中获取当前日期?

Gau*_*Pai 23 time date nsdate ios react-native

我正在构建我的第一个ReactNative iOS和Android应用程序.我是Swift和Obj-C的iOS编码器.如何使用ReactNative获取当前日期.

我应该使用Native Modules还是有一个ReactNative API,我可以从中获取这些数据?

Ada*_*son 41

React Native中的JavaScript运行时可以像访问任何其他环境一样访问日期信息.因此,简单地说:

new Date()
Run Code Online (Sandbox Code Playgroud)

...会给你当前的日期. 这是在JS中使用日期的MDN.

如果您想要一个好的JS库来更轻松地处理日期,请查看MomentJS.

  • 请记住,Android JSC 不能很好地处理日期,如果您需要国际化,您可能需要自定义 JSC 来处理“toLocaleDateString”之类的内容 https://github.com/react-community/jsc-android-buildscripts#国际变体 (2认同)

Sha*_*miq 9

I used {new Date()} was generating Invariant Violation: Objects are not valid error the following date function worked for me.

const getCurrentDate=()=>{
 
      var date = new Date().getDate();
      var month = new Date().getMonth() + 1;
      var year = new Date().getFullYear();
 
      //Alert.alert(date + '-' + month + '-' + year);
      // You can turn it in to your desired format
      return date + '-' + month + '-' + year;//format: d-m-y;
}
Run Code Online (Sandbox Code Playgroud)

For more info https://reactnativecode.com/get-current-date-react-native-android-ios-example It works for ios as well.


Irf*_*ani 7

我认为这应该有效;

new Date().toLocaleString()
Run Code Online (Sandbox Code Playgroud)

它将返回以您本地格式格式化的日期和时间(通常采用以下格式);

"6/22/2021, 2:59:00 PM"
Run Code Online (Sandbox Code Playgroud)