android – TimePickerDialog and AM or PM-ThrowExceptions

Exception or error:

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
    }
};
How to solve:

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

###

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.

###

Hi you could use your own format like this :

    String myFormat = "hh:mm a"; // your own format
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
    String  formated_time = sdf.format(calendar_time.getTime()); //format your time

I found that “a” is the code in formating time that represents AM-PM: http://www.tutorialspoint.com/java/java_date_time.htm

###

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

###

Try this simple method:

 void openTimeFragment() {
        TimePickerDialog mTimePicker;

        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        mTimePicker = new TimePickerDialog(YourActivity.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {



                String time = selectedHour + ":" + selectedMinute;

                  SimpleDateFormat fmt = new SimpleDateFormat("HH:mm");
        Date date = null;
        try {
            date = fmt.parse(time );
        } catch (ParseException e) {

            e.printStackTrace();
        }

        SimpleDateFormat fmtOut = new SimpleDateFormat("hh:mm aa");

          String formattedTime=fmtOut.format(date);

                edtTextTime.setText(formattedTime);
            }
        }, hour, minute, false);//No 24 hour time
        mTimePicker.setTitle("Select Time");
        mTimePicker.show();
    }

###

 private String getTime(int hr,int min) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY,hr);
        cal.set(Calendar.MINUTE,min);
        Format formatter;
        formatter = new SimpleDateFormat("h:mm a");
        return formatter.format(cal.getTime());
    }

###

Try this :

        Calendar calendar = Calendar.getInstance();
        calendar.set(0, 0, 0, hourOfDay, minute, 0);
        long timeInMillis = calendar.getTimeInMillis();
        java.text.DateFormat dateFormatter = new SimpleDateFormat("hh:mm a");
        Date date = new Date();
        date.setTime(timeInMillis);
        time.setText(dateFormatter.format(date));

###

If your expectation was to directly set AM/PM in the Time Picker Dialog box, there is a work around. This works if you pre-populate the EditText with current/default time.
– Before instantiating the dialog, increase the hour component by 12 if EditText has PM time value.

sref_Time3 is ampm value; sref_Time1 is hour component.

    if (sref_Time3.equals("PM")) {
        hour = hour + 12;
    } else if (sref_Time1.equals("12")) {
        hour = 0;
    }
    // Create a new instance of TimePickerDialog and return it
    return new TimePickerDialog(getActivity(), this, hour, minute,
               DateFormat.is24HourFormat(getActivity()));

Thanks & Regards.

Screen
Time Picker Dialog

###

This works for me :

TimePickerDialog timePickerDialog = new TimePickerDialog(AddFocusActivity.this, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            calendar.set(Calendar.MINUTE, minute);
            calendar.set(Calendar.HOUR,hourOfDay);
            time = calendar.get(Calendar.HOUR)
                    + ((calendar.get(Calendar.AM_PM) == Calendar.AM) ? "am" : "pm");

            Log.e("time",time);

        }
    },calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE), false);

###

private TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {    
            boolean isPM = (hourOfDay >= 12);
            tvTime.setText(String.format("%02d:%02d %s", (hourOfDay == 12 || hourOfDay == 0) ? 12 : hourOfDay % 12, minute, isPM ? "PM" : "AM"));
        }
    };

###

public static class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(0, 0, 0, hourOfDay, minute);
        textView.setText((String) DateFormat.format("hh:mm aaa", calendar));
    }
}


//For showing the dialog put below two lines where you want to call

TimePickerFragment timePickerFragment = new TimePickerFragment();
timePickerFragment.show(getSupportFragmentManager(), "TimePicker");

###

You can try my solution, I used “hh:mm a” format to set AM/PM time:

SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
String  formattedTime = formatter.format(myCalendar.getTime()); 
EditText.setText(formattedTime);

###

I know it’s too late for answer, and perfect answer is already selected, But I thought it is not quite clear for beginners, so posting my answer

editText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);

            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    String AM_PM;
                    if (selectedHour >=0 && selectedHour < 12){
                        AM_PM = "AM";
                    } else {
                        AM_PM = "PM";
                    }
                    editText.setText( selectedHour + ":" + selectedMinute+" "+AM_PM);
                }
            }, hour, minute, false);
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();
        }
    });

###

Try this, Hope it will help you

 int mHour;
 int mMin;
 StringBuilder stringBuilder = new StringBuilder();

 TimePickerDialog timePickerDialog = new TimePickerDialog(context, new  
 TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            mHour = hourOfDay;
            mMin = minute;

            String am_pm ;

            Calendar datetime = Calendar.getInstance();
            datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            datetime.set(Calendar.MINUTE, minute);

            am_pm = getTime(mHour,mMin);

            stringBuilder.append(" ");
            stringBuilder.append(am_pm);
            editTextDate.setText(stringBuilder);

        }

    }, mHour, mMin, false);

    timePickerDialog.show();



 public String getTime(int hr, int min) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY,hr);
    cal.set(Calendar.MINUTE,min);
    Format formatter;
    formatter = new SimpleDateFormat("h:mm a");
    return formatter.format(cal.getTime());
}

###

While using the TimeDialog to get the time and set it to an EditText, I have found that if the ‘minutes’ are less than 0, ex: 12:05, it giving like 12:5. Here in this code I’ve solved that issue and also properly using TimeDialog to get AM/PM if you want 12 hour format. Replace the your onTimeSet() with the following

public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    String period;
                    int hour = 0;
                    String minute;
                    if(selectedMinute >= 0 && selectedMinute < 10)
                        minute = "0" + selectedMinute;
                    else
                        minute = String.valueOf(selectedMinute);
                    if(selectedHour >= 0 && selectedHour < 12)
                        period = "AM";
                    else
                        period = "PM";
                    if(period.equals("AM")){
                        if(selectedHour == 0)
                            hour = 12;
                        else if(selectedHour >= 1 && selectedHour < 12)
                            hour = selectedHour;
                    }else if(period.equals("PM")){
                        if(selectedHour == 12)
                            hour = 12;
                        else if(selectedHour >= 13 && selectedHour <= 23)
                            hour = selectedHour - 12;
                    }
                    String time = hour+":"+minute+" "+period;
                    currentText.setText(time);
                }
            }, hour, minute, false);

###

This approach uses existing format functionality and the decision between am/pm and 24h format is based on if the timePickerDialog was opened with 24 hours support or not. Kotlin example.

val timePickerDialog = TimePickerDialog(
    requireContext(), TimePickerDialog.OnTimeSetListener { timePicker, hourOfDay, minutes ->

        val datetime = Calendar.getInstance()
        datetime.set(Calendar.HOUR_OF_DAY, hourOfDay)
        datetime.set(Calendar.MINUTE, minutes)

        val timeFormatAmPm = SimpleDateFormat("hh:mm aa")
        val timeFormat24Hours = SimpleDateFormat("HH:mm")

        timeEditTextView.setText(
            when (timePicker.is24HourView) {
                true -> timeFormat24Hours.format(datetime.time)
                false -> timeFormatAmPm.format(datetime.time)
            }
        )
    },
    currentHour, currentMinute, is24HourFormat
)

BR Matthias

###

@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
    SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", Locale.getDefault());
Calendar mCurrentTime = Calendar.getInstance();                
mCurrentTime.set(Calendar.HOUR_OF_DAY, selectedHour);
mCurrentTime.set(Calendar.MINUTE, selectedMinute);
mCurrentTime.clear(Calendar.SECOND);
String time = timeFormat.format(mCurrentTime.getTimeInMillis());
tvTime.setText(time.toLowerCase());}

Leave a Reply

Your email address will not be published. Required fields are marked *