以hh:mm格式显示时间选择器

时间:2015-09-01 09:00:16

标签: android date timepicker

我必须以hh:mm格式显示时间选择器点击编辑文本。所以我使用了下面的代码。

MainActivity.java:

  e6.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                    // TODO Auto-generated method stub
                    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
                    Calendar mcurrentTime = Calendar.getInstance();
                    int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                    int minute = mcurrentTime.get(Calendar.MINUTE);
                    TimePickerDialog mTimePicker;
                    mTimePicker = new TimePickerDialog(AddFlight.this, new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                            e6.setText(selectedHour + ":" + selectedMinute);

                        }
                    }, hour, minute, true);//Yes 24 hour time
                    mTimePicker.setTitle("Select Time");
                    mTimePicker.show();

            }
        });

它运行良好并显示时间选择器。但是我的问题是,当我选择时间戳中的04:15时,它显示为4:15。它之前不包含0我需要用hh:mm格式显示时间选择器。

任何人都可以帮助我。谢谢。

4 个答案:

答案 0 :(得分:10)

刚才我引用了这个post并更改了单行:

这一行

  

e6.setText(selectedHour +":" + selectedMinute);

  

e6.setText(String.format("%02d:%02d",selectedHour,   selectedMinute));

答案 1 :(得分:2)

只需将文字设置为"%02d:%02d"如下:

e6.setText(String.format("%02d:%02d", selectedHour, selectedMinute));

希望这可能会对你有所帮助

答案 2 :(得分:0)

你可以尝试这种方式......

mTimePicker = new TimePickerDialog(AddFlight.this, new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
        String formattedTime = "";
        String sHour = "00";
        // converting hour to tow digit if its between 0 to 9. (e.g. 7 to 07)
        if(selectedHour < 10)
            sHour = "0"+selectedHour;
        else
            sHour = String.valueOf(selectedHour);


        e6.setText(sHour + ":" + selectedMinute);
    }
}, hour, minute, true);

答案 3 :(得分:0)

只需使用此方法,

private String getDD(int num) {
   return num > 9 ? "" + num : "0" + num;
}