0

I am currently working on a reminders app and I added a DateTimePickerModal from the package react-native-modal-datetime-picker and I wanted to know how to format the data...

This is the code for the component

<DateTimePickerModal
    isVisible={this.state.modalVisible}
    mode="datetime"
    onConfirm={onConfirm}
    onCancel={onCancel}                                                                                                        
/>

Code for the onConfirm function

const onConfirm = (dateAndTime) => {
     this.setState({ dateAndTime: dateAndTime.toString() });
     hideModal();                   
};

The data I'm getting:

Converted into string: Mon May 03 2021 16:01:37 GMT+0530 (IST)

Without converting it to string: 2021-05-06T09:31:37.000Z

If you have any idea on how to do this please let me know...Thanks in advance!

Vibha
  • 27
  • 5
  • react-native datetime picker returns `Date` object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date So, you can use the built-in methods to format your date https://stackoverflow.com/a/30272803/5793132 – Uğur Eren May 03 '21 at 10:11

1 Answers1

1

Yes you are on the right way

Just create a function to format Date like this

 const FormatDate = (data) => {
    let dateTimeString =
      data.getDate() +
      '-' +
      (data.getMonth() + 1) +
      '-' +
      data.getFullYear() +
      ' ' +
      data.getHours() +
      ':' +
      data.getMinutes();
    return dateTimeString; // It will look something like this 3-5-2021 16:23
  };

Then for setting state do like this

this.setState({ dateAndTime: FormatDate(dateAndTime) });

Here is a Snack to see working example..It will run on iOS and Android only as

DateTimePicker is not supported on: web

Kartikey Vaish
  • 1,847
  • 1
  • 3
  • 19