如何从Firestore的Timestamp中排除日期仅展示时分秒
实现Firestore Timestamp仅展示时分秒的方案
你原来直接调用Date.toString()会输出完整的日期字符串,只需要对Timestamp转换得到的Date对象做自定义格式化即可实现仅提取时分秒。
方案1:SimpleDateFormat(兼容全版本Android)
该方式适配所有Android系统版本,使用示例如下:
import java.text.SimpleDateFormat; import java.util.Locale; import java.util.TimeZone; // 初始化时分秒格式化工具,HH为24小时制,需要12小时制可替换为hh SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()); // 显式指定时区为东八区,和你示例输出的GMT+08:00匹配,避免时区偏差 timeFormatter.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); // 格式化时间后设置到控件 String formatTime = timeFormatter.format(employeeModel.getTime_in().toDate()); holder.binding.tvTimeIn.setText(formatTime);
方案2:DateTimeFormatter(Java 8+ 推荐)
如果你的项目开启了Java 8核心库desugaring适配,推荐用该方案,不存在SimpleDateFormat的线程安全问题:
import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; // 转换Date为时区时间对象 ZonedDateTime zonedDateTime = employeeModel.getTime_in().toDate() .toInstant() .atZone(ZoneId.of("GMT+8:00")); // 格式化输出时分秒 String formatTime = zonedDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")); holder.binding.tvTimeIn.setText(formatTime);
注意事项
- 若应用需要适配全球多时区,不要写死GMT+8:00,替换为当前用户系统的默认时区即可
- 格式符大小写严格区分:
HH对应24小时制(00-23),hh对应12小时制(01-12),写错会导致时间显示不符合预期
内容的提问来源于stack exchange,提问作者Patrick
相关产品推荐
相关产品推荐

