如何将Time Picker Compose获取的时分转换为时间戳毫秒值?
将时分转换为对应毫秒时间戳
我使用Time Picker Compose组件获取时分信息(如23:50),需要将其转换为对应的毫秒时间戳。规则是:
- 若目标时分在当前时间之后,使用当天的该时间生成时间戳(例:当前为2023-08-15 18:06,目标23:50对应1692139800000)
- 若目标时分在当前时间之前,使用次日的该时间生成时间戳(例:当前为2023-08-15 18:06,目标12:05对应1692183900000)
推荐实现方式(基于Java Time API)
直接利用Java 8+的时间API处理,自动兼容时区、夏令时等边界情况,代码更简洁可靠:
import java.time.Clock import java.time.LocalTime import java.time.ZoneId import java.time.ZonedDateTime fun getMillisFromHrsMins(clock: Clock, timeZoneId: ZoneId, hours: Int, minutes: Int): Long { // 获取当前带时区的时间实例 val currentZoned = ZonedDateTime.now(clock).withZoneSameInstant(timeZoneId) // 构造目标时分的LocalTime val targetTime = LocalTime.of(hours, minutes) // 拼接成当天的目标时间 var targetZoned = currentZoned.toLocalDate().atTime(targetTime).atZone(timeZoneId) // 若目标时间早于当前时间,自动切换到次日 if (targetZoned.isBefore(currentZoned)) { targetZoned = targetZoned.plusDays(1) } // 转换为毫秒级时间戳 return targetZoned.toInstant().toEpochMilli() } // 测试示例 fun main() { // 模拟当前时间为2023-08-15 18:06:00(UTC+8时区) val testClock = Clock.fixed(java.time.Instant.parse("2023-08-15T10:06:00Z"), ZoneId.of("Asia/Shanghai")) println(getMillisFromHrsMins(testClock, ZoneId.of("Asia/Shanghai"), 23, 50)) // 输出1692139800000 println(getMillisFromHrsMins(testClock, ZoneId.of("Asia/Shanghai"), 12, 5)) // 输出1692183900000 }
基于你现有代码逻辑的补全方案
如果坚持用秒数计算的思路,先实现nowToMidnightSeconds函数,再补全时间戳计算逻辑:
import java.time.Clock import java.time.ZoneId import java.time.ZonedDateTime fun nowToMidnightSeconds(clock: Clock, timeZoneId: ZoneId): Long { val currentZoned = ZonedDateTime.now(clock).withZoneSameInstant(timeZoneId) // 计算当前时间到次日午夜的秒数 val nextMidnight = currentZoned.toLocalDate().plusDays(1).atStartOfDay(timeZoneId) return java.time.Duration.between(currentZoned, nextMidnight).seconds } fun getMillisFromHrsMins(clock: Clock, timeZoneId: ZoneId): Long { val hours = 12 val minutes = 5 val targetDaySeconds = hours * 3600L + minutes * 60L // 用Long避免整数溢出 val currentZoned = ZonedDateTime.now(clock).withZoneSameInstant(timeZoneId) val nowDaySeconds = currentZoned.toLocalTime().toSecondOfDay().toLong() // 计算从当前时间到目标时间的总秒数 val totalSecondsFromNow = if (targetDaySeconds >= nowDaySeconds) { targetDaySeconds - nowDaySeconds } else { nowToMidnightSeconds(clock, timeZoneId) + targetDaySeconds } // 当前时间戳加上间隔秒数,转换为毫秒 return currentZoned.toInstant().toEpochMilli() + totalSecondsFromNow * 1000 }
注意:手动计算秒数容易忽略时区调整(如夏令时导致的23/25小时天数),推荐优先使用第一种API方案。
内容的提问来源于stack exchange,提问作者BRDroid
相关产品推荐
相关产品推荐

