How to get the Current Date in ReactNative?
Asked Answered
M

5

40

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 ?

Mita answered 17/5, 2016 at 8:49 Comment(4)
Just new Date().toDateString(), reference: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Deeprooted
reminds me this: howtodoinjava.files.wordpress.com/2013/04/use-jquery.gifDeeprooted
Doesn't work. I am naive in JS and React. Could you please be more elaborate ?Mita
Use Luxon, a good and modern JS-Library to make working with dates even easier, check out moment.github.io/luxon and moment.github.io/luxon/docs/manual/install.htmlOutrider
K
70

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.

Kor answered 17/5, 2016 at 9:5 Comment(1)
Keep in mind the Android JSC doesn't work well with dates, and you might need a custom JSC to handle stuffs like toLocaleDateString if you need internationalisation github.com/react-community/…Pinter
T
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;
}

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

Tibold answered 5/5, 2020 at 21:29 Comment(3)
That will return d-m-y, there is no padding.Fixer
@Fixer you can change it to your desired format and can design it as well.Tibold
To clarify, the return statement returns d-m-y, your comment says it returns dd-mm-yyyy. It's your stated format.Fixer
R
7

I think this should work;

new Date().toLocaleString()

It will return date and time formatted in your local format (usually in the below format);

"6/22/2021, 2:59:00 PM"
Raft answered 22/6, 2021 at 9:29 Comment(0)
N
0

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

Narcisanarcissism answered 25/1, 2020 at 9:26 Comment(0)
A
0

To Get the current date-time using Date function you just need to call it in the following ways

const date = new Date().getDate(); //To get the Current Date
Amena answered 7/3 at 10:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.