gpt4 book ai didi

android - 时间选择器显示时间如 4 :7 instead of 04:07

转载 作者:IT老高 更新时间:2023-10-28 23:08:09 28 4
gpt4 key购买 nike

我有一个时间选择器功能,可以在 EditText 中设置时间。但它显示的格式不合适。例如,下午 4:07 显示为 4:7。每当数字小于 10 时,它会自动删除 0。请帮帮我。 我的代码是

        if (v == btnTimePicker1)
{

// Process to get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);

// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
txtTime1.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
tpd.show();




}

最佳答案

只需换行:

txtTime1.setText(hourOfDay + ":" + minute);

到:

txtTime1.setText(String.format("%02d:%02d", hourOfDay, minute));

一切都会好起来的。

如果您想要一个 12 小时制而不是 24 小时制,则将该行替换为以下内容:

int hour = hourOfDay % 12;
if (hour == 0)
hour = 12;
txtTime1.setText(String.format("%02d:%02d %s", hour, minute,
hourOfDay < 12 ? "am" : "pm"));

或者你可以用 2 行代码完成:

int hour = hourOfDay % 12;    
txtTime1.setText(String.format("%02d:%02d %s", hour == 0 ? 12 : hour,
minute, hourOfDay < 12 ? "am" : "pm"));

关于android - 时间选择器显示时间如 4 :7 instead of 04:07,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22807226/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com