0
votes

I am using react-native-modal-datetime-picker library to get the time from the user. But I am getting time with complete date how should i get time from that. Following is my code to get time.

    _showDateTimePicker = () => this.setState({ isDateTimePickerVisible: true });

            _hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false });

            _handleDatePicked = (time) => {
                console.log('A time has been picked: ', time);
                this._hideDateTimePicker();
            };

                <DateTimePicker
                    isVisible={this.state.isDateTimePickerVisible}
                    onConfirm={this._handleDatePicked}
                    onCancel={this._hideDateTimePicker}
                    mode='time'
                />

I am getting the timePicker coming on screen but after selecting a time it is showing a complete date with selected time but I want only time
The output I am getting is,

A time has been picked:  Tue Feb 05 2019 12:25:00 GMT+0530 (India Standard Time)
3
Use Javascript Date object methods. e.g getHours(),getMinutes(),getSeconds() - Rupesh Bramhankar

3 Answers

4
votes

react-native-modal-datetime-picker actually returns a Javascript Date object

You can get access to the different values by using the properties of the Date object https://www.w3schools.com/jsref/jsref_obj_date.asp

You'll want to use getHours() getMinutes() and getSeconds() to pull the relevant information from your date.

let date = new Date();

let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
console.log(`${hours}:${minutes}:${seconds}`)

// how to handle the cases where time is one digit
function makeTwoDigits (time) {
  const timeString = `${time}`;
  if (timeString.length === 2) return time
  return `0${time}`
}

console.log(`${makeTwoDigits(hours)}:${makeTwoDigits(minutes)}:${makeTwoDigits(seconds)}`)

To handle the case when time returns a single digit all you need to do is convert the value you get into a string, check its length, and add a 0 to the front if it isn't long enough.

Here is a snack with the working code https://snack.expo.io/@andypandy/date-time-modal-picker

1
votes

here, time returned by react-native-modal-datetime-picker is a JavaScript Date object, so you can get hours, minutes and seconds like this:

 _handleDatePicked = (time) => {
        const hours = time.getHours();
        const minutes = time.getMinutes();
        const seconds = time.getSeconds();
        console.log('A time has been picked: ', hours, minutes, seconds);
        this._hideDateTimePicker();
    };     
0
votes

You can use new Date(). let date = new Date(time).

For Hours:

date.getHours()

For Minutes:

date.getMinutes()