You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TextView中正确显示hh:mm格式时间?修复时分补零缺失问题

修复TextView显示时间时个位数分钟缺失前导零的问题

这个问题很常见,本质是你可能直接把小时和分钟的数值拼接成字符串了——当分钟是1-9的个位数时,自然不会自动补前导零。给你几个简单靠谱的解决办法:

方法1:用String.format()快速格式化

如果你的时间是已经拆分好的小时和分钟整数,直接用格式化字符串补零最方便:

int hour = 12;
int minute = 3;
// %02d 表示将整数格式化为两位,不足两位时用0填充
String formattedTime = String.format("%02d:%02d", hour, minute);
yourTextView.setText(formattedTime);

这样不管分钟是3还是03,都会统一显示成两位的格式。

方法2:用时间格式化类(适合从Date/Calendar/LocalTime获取时间的场景)

如果你的时间是从日期对象里来的,推荐用专门的时间格式化工具,避免手动拼接出错:

兼容Android全版本(用SimpleDateFormat)

Calendar calendar = Calendar.getInstance();
// 指定格式为"HH:mm",其中mm强制显示两位分钟
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
String formattedTime = sdf.format(calendar.getTime());
yourTextView.setText(formattedTime);

Android 8.0+推荐用DateTimeFormatter(线程安全,更现代)

// 比如你要构造12:03的时间
LocalTime targetTime = LocalTime.of(12, 3);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm", Locale.getDefault());
String formattedTime = targetTime.format(formatter);
yourTextView.setText(formattedTime);

避坑提醒

千万别再用hour + ":" + minute这种方式拼接字符串了,这种写法完全没办法处理个位数补零的场景,就是你现在出问题的根源。

内容的提问来源于stack exchange,提问作者Radesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:00:58