2

I have implemented a react-native-datepicker, and it is displaying correctly and the default date is correct as the initial state is:

date: new Date()

However, when I press the icon to choose a date, all the dates are greyed out, and you can scroll but when you let go it just goes back and won't let you choose a date.

Any idea why I am having this problem?

<DatePicker
  style={{width: 200}}
  mode="date"
  date={this.state.date}
  format="DD-MM-YYYY"
  minDate={this.state.date}
  maxDate="01-01-2030"
  confirmBtnText="Confirm"
  cancelBtnText="Cancel"
  onDateChange={(d) => {this.setState({date: d})}}
/>
ridvanaltun
  • 2,595
  • 2
  • 15
  • 28
LondonMassive
  • 367
  • 2
  • 5
  • 20

1 Answers1

1

This is because new Date() isn't in the format you want. new Date() infact returns an Object. It is hard to convert this object to the required format, but here is a link to a solution on Stack Overflow, just in case.

I recommend using libraries like moment.js because it's easy to format dates using it and you can do a lot more.

In your case, I suggest replacing the initial state value to:

{date: moment().format('DD-MM-YYYY')}

Beware! Setting minDate={this.state.date} will restrict you from selecting older dates, i.e once you select a future date, you can never select a date before that again!

Vignesh V Pai
  • 699
  • 4
  • 7
  • Ok, I have installed moment and made the changes you said. However, I get quite a large error when I open the calendar. Could you show how you would implement moment into this calendar? – LondonMassive Mar 12 '20 at 15:08
  • First, set the initial state as shown below. ```this.state = {date: moment().format('DD-MM-YYYY')};``` Then, your DatePicker would be something like this: ``` { this.setState({date: d}); }} />``` – Vignesh V Pai Mar 13 '20 at 06:11