How do I set AM/PM in a TimePicker?

后端 未结 5 1781
有刺的猬
有刺的猬 2020-12-18 18:40

I am using a TimePicker in my app. Whenever the user opens the screen with the TimePicker, I initialize it with the current time. When I do this, the TimePicker shows AM ins

5条回答
  •  不知归路
    2020-12-18 18:55

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

提交回复
热议问题