简体   繁体   中英

Android Time Picker Format

I am using TimePicker and in picker it showing time in 24 hour format, which is good, but when i select ...

Getting - 9:5 PM

Requirement 1 - 09:05 PM

Requirement 2 - 21:05

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

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

   .......


    TimePickerDialog.OnTimeSetListener lisTime = new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // TODO Auto-generated method stub
            String hour = "";
            String meridiem = "";
            Calendar datetime = Calendar.getInstance();
            datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            datetime.set(Calendar.MINUTE, minute);

            if (datetime.get(Calendar.AM_PM) == Calendar.AM)
                meridiem = "AM";
            else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
                meridiem = "PM";

            hour = (datetime.get(Calendar.HOUR) == 0) ?"12":String.valueOf(datetime.get(Calendar.HOUR));
            editTime.setText(hour + ":" + String.valueOf(minute) + " " + meridiem);
        }
    };

So where i have to make changes in my code, to get this done !

For Requirement 1: use below code:

String date="9:5 PM";

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("hh:mm aa",Locale.getDefault());

        try {
            Log.e("",""+new SimpleDateFormat("HH:mm",Locale.getDefault()).format(simpleDateFormat.parse(date)));

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

For Requirement 2: use below code:

 private String pad(int value){

            if(value<10){
                return "0"+value;
            }


            return ""+value;            
        }

EDITED:

Replace below lines

            editTime.setText(hour + ":" + String.valueOf(minute) + " " + meridiem);

to

String date=pad(Integer.parseInt(hour)) + ":" + pad(minute) + " " + meridiem;

         SimpleDateFormat simpleDateFormat=new SimpleDateFormat("hh:mm aa",Locale.getDefault());

        try {
            editTime.setText(""+new SimpleDateFormat("HH:mm",Locale.getDefault()).format(simpleDateFormat.parse(date)));

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM