Kotlin中如何内联格式化LocalTime并获取指定短时间格式?
解决方案
核心问题是你混淆了LocalTime时间对象和格式化后的字符串文本——你之前的类型不匹配错误,正是因为试图把format()返回的String赋值给LocalTime类型变量导致的。以下是两种场景的具体处理方式:
1. 直接内联获取短格式字符串(用于展示)
如果你的需求只是得到15:05这样的文本格式,直接调用LocalTime.format()方法,搭配指定格式的DateTimeFormatter即可,结果存为String类型:
import java.time.LocalTime import java.time.format.DateTimeFormatter // 内联格式化,直接得到目标格式的字符串 val timeOutgoingStr: String = LocalTime.now().plusHours(1).format(DateTimeFormatter.ofPattern("HH:mm"))
其中HH:mm是格式规则:HH代表24小时制的两位小时数,mm代表两位分钟数,刚好满足你的短格式需求。
2. 保留LocalTime类型但截断精度(仅保留到分钟)
如果你需要继续使用LocalTime类型,但希望它的秒、毫秒都置为0(后续格式化时自然不会显示),可以用truncatedTo()方法截断到分钟单位:
import java.time.LocalTime import java.time.temporal.ChronoUnit import java.time.format.DateTimeFormatter // 截断到分钟,得到秒和毫秒为0的LocalTime对象 val timeOutgoing: LocalTime = LocalTime.now().plusHours(1).truncatedTo(ChronoUnit.MINUTES) // 后续需要展示时再格式化 val displayStr = timeOutgoing.format(DateTimeFormatter.ofPattern("HH:mm"))
内容的提问来源于stack exchange,提问作者JamieRhys
相关产品推荐
相关产品推荐

