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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37271356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:05:00  来源:igfitidea点击:

How to get the Current Date in ReactNative?

iosdatetimereact-nativensdate

提问by Gautham Pai

I am building my first ReactNative iOS and Android app. I am an iOS coder with Swift and Obj-C. How do I fetch the current date using ReactNative.

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

Shall I use Native Modules or is there an ReactNative API from which I can get this data ?

我应该使用本机模块还是有一个 ReactNative API 可以从中获取这些数据?

回答by Adam Terlson

The JavaScript runtime in React Native has access to date information just like any other environment. As such, simply:

React Native 中的 JavaScript 运行时可以像任何其他环境一样访问日期信息。因此,只需:

new Date()

... will give you the current date. Here's the MDNon working with dates in JS.

...会给你当前的日期。 这是在 JS 中处理日期的 MDN

If you want a good JS library to make working with dates even easier, check out MomentJS.

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

回答by Gautham Pai

if you get currentmilisecdate use + new Date()and if get current use new Date()I hope Help to you GoodLuk

如果您获得当前milisec日期使用+ new Date()并且获得当前使用new Date()我希望对您有所帮助 GoodLuk

回答by Shamiq

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

我使用的{new Date()}是生成Invariant Violation: Objects are not valid错误以下日期函数对我有用。

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: dd-mm-yyyy;
}

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

有关更多信息https://reactnativecode.com/get-current-date-react-native-android-ios-example它也适用于 ios。