Files
yusheng-android/MainModule/src/main/java/com/xscm/modulemain/utils/CountdownTimer.kt
2025-12-05 10:48:31 +08:00

57 lines
2.0 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.xscm.modulemain.utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
class CountdownTimer {
private var job: Job? = null
private val _timeLeft = MutableStateFlow(0L)
val timeLeft: StateFlow<Long> = _timeLeft
fun startCountdown(endTimestamp: Long, scope: CoroutineScope) {
job?.cancel()
job = scope.launch {
while (true) {
val currentTime = System.currentTimeMillis() / 1000
val remainingTime = (endTimestamp - currentTime) * 1000 // 转换为毫秒
if (remainingTime <= 0) {
_timeLeft.value = 0
break
}
_timeLeft.value = remainingTime
delay(1000)
}
}
}
fun stop() {
job?.cancel()
}
/**
* 将毫秒数格式化为 HH:MM:SS 格式的时间字符串
* @param milliseconds 毫秒数(支持 0、负数、超大数值
* @return 格式化结果,如 3670000 毫秒 → 01:01:10125000 毫秒 → 00:02:05
*/
fun formatTime(milliseconds: Long): String {
// 1. 处理负数/0转为非负避免时间为负
val nonNegativeMs = if (milliseconds < 0) 0 else milliseconds
// 2. 计算总秒数向下取整不足1秒按0算
val totalSeconds = (nonNegativeMs / 1000).toInt()
// 3. 拆分 小时、分钟、秒
val hours = totalSeconds / 3600 // 1小时=3600秒
val remainingSecondsAfterHour = totalSeconds % 3600 // 小时剩余秒数
val minutes = remainingSecondsAfterHour / 60 // 分钟
val seconds = remainingSecondsAfterHour % 60 // 秒
// 4. 格式化HH/MM/SS 均补0为2位如 1小时1分5秒 → 01:01:05
return String.format("%02d:%02d:%02d", hours, minutes, seconds)
}
}