Younghak Jang
Younghak Jang

Reputation: 489

how to add minutes to Date() in react-native?

I want to add 5 minutes to current time and store it to this.state.date.

However,

this.setState({
    date: new Date() + new Date(0,0,0,0,0,5,0),
});

gives me some strange error, saying

`props.date.getTime is not a function. (In 'props.date.getTime()', 'props.date.getTime' is undefined)

DatePickerIOS_render DatePickerIOS.ios.js:125

EDITED: According to this post I also tried below,

this.setState({
    date: this.state.date.setMinutes((new Date()).getMinutes()+5)
});

but it still gives me the same error message. What is the correct way to add minutes to Date() in react-native?

Btw, I'm using datepickerios on another part of the app, and not sure why the error is related to DatePickerIOS.ios.js in the first place. The other part of the app which actually uses the DatePickerIOS works fine without error.

EDITED AGAIN:

Below is the full function. This function is called from a SegmentedControlIOS which has values ['5min from now', '15min from now', '30min from now', 'custom'].

_onTimeChange = (event) => {

    switch (event.nativeEvent.selectedSegmentIndex) {
        case 0:
        // 5min
            return this.setState({
                date: this.state.date.setMinutes((new Date()).getMinutes()+5),
                time: this.state.date.toLocaleTimeString()
            });
        case 1:
        // 15min
            return this.setState({
                date: this.state.date.setMinutes((new Date()).getMinutes()+15),
                time: this.state.date.toLocaleTimeString()
            });
        case 2:
        // 30min
            return this.setState({
                date: this.state.date.setMinutes((new Date()).getMinutes()+30),
                time: this.state.date.toLocaleTimeString()
            });
        case 3: 
        // show modal with datepicker (this one works fine)
            return this.setModalVisible(true);
    }
  }

What happens: If I change selection from the segmented control once, a yellow warning bar with props error message is shown at the bottom of my simulator. If I change selection once again, then the red screen shows up with '_this5.state.date.setMinutes is not a function'.

So it looks like

date: this.state.date.setMinutes((new Date()).getMinutes()+5)

does add minutes, but when I do it twice it ends up in error. Please help!

Upvotes: 2

Views: 14832

Answers (1)

leo7r
leo7r

Reputation: 10588

Try this:

var d = new Date(); // get current date
d.setHours(d.getHours(),d.getMinutes()+5,0,0);

EDIT

var d = new Date(); // get current date
d.setHours(d.getHours(),d.getMinutes()+5,0,0);
this.setState(date:d,time:d.toLocaleTimeString());

Upvotes: 3

Related Questions