TimePickerDialog and AM or 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();
    }

I was running into the same problem. I have a TimePicker in my app where after you choose a time and hit a button you'll be taken to a screen that showed what time was chosen. The "time" chosen was correct but sometimes the AM/PM value would be opposite of what was chosen. I finally fixed it by changing what I was storing for the "hrs" argument from the TimePicker.

private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() 
{   
    @Override
    public void onTimeSet(TimePicker view, int hrs, int mins)
    {
        hour = hrs;
        minute = mins;

        c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hour);
        //instead of c.set(Calendar.HOUR, hour);
        c.set(Calendar.MINUTE, minute);

Now when I hit the button to go to the next screen it properly showed the correct AM/PM value chosen.


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 );
}

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().