How to get AM/PM from TimePickerAndroid in React Native

Viewed 2413

I'm using TimePickerAndroid of React Native and using 12hours timing,

So, it is working fine and shows AM/PM to select and picker returned me hours and minutes, but I did not found anyway to get that AM is selected or PM, code is below.

async showTimePicker() {
    const { action, minute, hour } = await TimePickerAndroid.open({
        is24Hour: false,
    });
    if (action === TimePickerAndroid.dismissedAction) {
        return;
    }
    const selectedTime = `${hour}:${minute}`;
    this.setState({ selectedTime })
}

I just need to know that AM is selected or PM everything else is working fine.

official docs for reference.

Thank you.

3 Answers

Flag is just for showing to the user inside the timer popup. Once user selects the time, It will give you 24 hour format only.. If user select "2:00 PM", the return value will be 14 hours and 00 minutes. while displaying in any other place, You can just convert into AM/PM and display it.

Expect only 24 hours format from the TimePickerAndroid.

You can use a condition to display AM/PM, here I added an example code segment for you. Sriraman's answer also explained to use this kind of method.

async showTimePicker() {

var { action, minute, hour } = await TimePickerAndroid.open({      
  is24Hour: false,
});


if (action === TimePickerAndroid.dismissedAction) {
    return;
}
// setting AM/PM and hour to 12 by checking condition
let am_pm = 'AM';

if(hour>11){
  am_pm = 'PM';
  if(hour>12){
    hour = hour - 12;
  }
}

if(hour == 0){
  hour = 12;
}
  const selectedTime = `${hour}:${minute} ${am_pm}` ;
  this.setState({ selectedTime })
}

Whatever bool value you set for is24Hour, the time picker returns hours in the 24 hour format. That is, if you select 8:00 PM, the time picker returns the JSON Object {action:'timeSetAction', hour:20, minute:0}. You're right that the official docs doesn't show this.

Related