How do I set AM/PM in a TimePicker?

旧街凉风 提交于 2019-11-29 09:08:26

You'll have to use Calendar.HOUR_OF_DAY instead of Calendar.HOUR.

i.e., timePicker.setCurrentHour() always expects the argument in 24-hour format. Unfortunately, this fact is not documented properly in the API documentation.

Arindam Mukherjee

I think you have to override the onTimeSet() method of the Timepicker. Check this link

TimePickerDialog and AM or PM

May it helps you..

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));
Rishi
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute) {
    if(hourOfDay>=0 && hourOfDay<12){
        time = hourOfDay + " : " + minute + " AM";
    } else {
        if(hourOfDay == 12){
            time = hourOfDay + " : " + minute + "PM";
        } else{
            hourOfDay = hourOfDay -12;
            time = hourOfDay + " : " + minute + "PM";
        }
    }

    deliveryTime.setText(time);
}
rakshi059

First, get an instance of the Calendar class, then use HOUR_OF_DAY to get the hour. HOUR_OF_DAY will be in 24-hour format so just assign that to a variable and then check whether that int is greater than 0 and less than 12. If this condition is true then append AM or else PM. Because HOUR_OF_DAY is 24-hour format, the PM hours will be displayed as 13,14 so to handle this, just subtract the HOUR_OF_DAY by 12. Here is the code:

Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour < 12 && hour >= 0) {
    tv.setText(hour + " AM");
} else {
    hour -= 12;
    if(hour == 0) {
        hour = 12;
    }
    tv.setText(hour + " PM");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!