I'm so confused what's going on. I just implemented react-native-datetimepicker/datetimepicker for a user to select their birthday.
If I select June 8, 2000 -> the date returned is 2000-06-09T00:00:00.000Z, which means the users birthday is set for June 9, 2000.
here is the element:
<DateTimePicker
value={this.props.date}
mode={this.props.mode}
display="calendar"
onChange={(event, date) => {
this.handleDatePicked(event, date)
}}
/>
async handleDatePicked(event, date) {
console.log(new Date(date))
await this.props.onSelect(this.props.propName, date)
await this.changeState()
}
console.log(date) logs 2000-06-09T00:00:00.000Z
console.log(new Date(date)) logs 2000-06-09T00:00:00.000Z
BUT! console.log(new Date(date).getDate()) logs 8
And when I reopen the calendar, it is set on June 8, 2000.
🤯
My mind is exploding -- what is going on here? June 8, 2000 is only for the example - it's constantly off by 1 day no matter what day, month or year is selected. My hypothesis is something to do with timezone maybe? Any help is greatly appreciated!
This is because Date.getDate() returns the day and month according to local time. The date object you’ve provided is set to UTC time, which means when the date is converted to your local time zone it is actually the day before.
To fix this problem, set the timeZoneOffsetInMinutes prop of your date picker.
Unfortunately, this prop has known implementation problems on Android. A good alternative may be to avoid the prop entirely, and instead use a date library like date-fns to manipulate the time zone of the outputted date object.