ANDROID时间选择器如何以小时和分钟显示两个数字

时间:2016-07-04 08:42:34

标签: java android android-studio timepicker android-timepicker

大家好,我想点击按钮时显示,两小时一分钟。

我的代码是:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int hour= timePicker.getCurrentHour();
        int minute=timePicker.getCurrentMinute();

        Toast.makeText(MainActivity.this,"CLOCK--> "+ String.valueOf(hour)+":"+String.valueOf(minute),Toast.LENGTH_LONG).show();

    }
});       

但输出是例如" 9:8"。

我想要展示" 09:08"。

抱歉我的英文=)

4 个答案:

答案 0 :(得分:5)

你可以像这样使用:

String time = "";
    time = new SimpleDateFormat("HH:mm").format(new Date(System.currentTimeMillis()));

答案 1 :(得分:0)

Try this
Toast.makeText(MainActivity.this,"CLOCK--> "+ String.format("%02d:%02d", hour, minute),Toast.LENGTH_LONG).show();

答案 2 :(得分:0)

如果数字低于10

,则在左侧添加零
String hrstr = hour < 10 ? //If hour is lower than 10, add a zero on the left 
    '0' + hour : hour;
String minstr = min < 10 ? //If minute is lower than 10, add a zero on the left
    '0' + min : min;
Toast.makeText(MainActivity.this,"CLOCK--> "+ hrstr +":"+minstr,Toast.LENGTH_LONG).show();

答案 3 :(得分:0)

尝试一下

Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(mContext, new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
        yourView.setText(String.format("%02d:%02d", selectedHour, selectedMinute));
    }
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();