How to get the Current Date in ReactNative?

我怕爱的太早我们不能终老 提交于 2021-01-20 18:51:08

问题


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.

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


回答1:


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

new Date()

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

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




回答2:


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

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




回答3:


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



来源:https://stackoverflow.com/questions/37271356/how-to-get-the-current-date-in-reactnative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!