I have a TimePickerDialog with is24Hour set to false since I want to present the end-user with the more familiar 12 hour format. When the hour, minute and AM PM indicator are set and the time is returned how can I identify whether the end-user has selected AM or PM?
This is what I have for the listener:
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
mHour = hourOfDay;
mMinute = minute;
// mIsAM = WHERE CAN I GET THIS VALUE
}
};
The time can be selected by hour, minute, and AM/PM picker columns. The AM/PM mode is determined by either explicitly setting the current mode through setIs24Hour(boolean) or the widget attribute is24HourFormat (true for 24-hour mode, false for 12-hour mode).
To provide a widget for selecting a time, use the Time Picker widget , you to select the time of day in either 24 hour or AM/PM mode. The time consists of hours, minutes and clock format. Android provides this functionality through TimePicker class.
You can get AM/PM from Timepicker using following method. Timepicker is a viewgroup. That's why we can get its child view index 2 which demonstrates AM/PM is actually a button. So we can get its text.
The hourOfDay
will always be 24-hour. If you opened the dialog with is24HourView
set to false
, the user will not have to deal with 24-hour formatted times, but Android will convert that to a 24-hour time when it calls onTimeSet()
.
This worked for me:
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String am_pm = "";
Calendar datetime = Calendar.getInstance();
datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
datetime.set(Calendar.MINUTE, minute);
if (datetime.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
String strHrsToShow = (datetime.get(Calendar.HOUR) == 0) ?"12":datetime.get(Calendar.HOUR)+"";
((Button)getActivity().findViewById(R.id.btnEventStartTime)).setText( strHrsToShow+":"+datetime.get(Calendar.MINUTE)+" "+am_pm );
}
a neat toast message with what user selected showing proper HH:MM format
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String AM_PM = " AM";
String mm_precede = "";
if (hourOfDay >= 12) {
AM_PM = " PM";
if (hourOfDay >=13 && hourOfDay < 24) {
hourOfDay -= 12;
}
else {
hourOfDay = 12;
}
} else if (hourOfDay == 0) {
hourOfDay = 12;
}
if (minute < 10) {
mm_precede = "0";
}
Toast.makeText(mContext, "" + hourOfDay + ":" + mm_precede + minute + AM_PM, Toast.LENGTH_SHORT).show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With