package com.sw.inbound.utils import kotlinx.coroutines.delay import kotlinx.coroutines.flow.flow import timber.log.Timber import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import kotlin.math.abs /** * 时间格式化工具类 */ object DateTimeUtils { /** * 获取完整中文日期格式(示例:2025年6月11日 星期三) */ fun getChineseDateString(date: Date = Date()): String { return SimpleDateFormat("yyyy年M月d日 EEEE", Locale.CHINA).format(date) } /** * 获取标准时间格式 */ fun getDateTimeString(date: Date = Date()): String { return SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(date) } /** * 获取带时间的完整中文格式(示例:2025年06月11日 星期三 14:30) */ fun getChineseDateTimeString(date: Date = Date()): String { return SimpleDateFormat("yyyy年MM月dd日 EEEE HH:mm", Locale.CHINA).format(date) } // 使用线程安全的日期格式化(避免 SimpleDateFormat 的线程安全问题) private val dateFormat by lazy { SimpleDateFormat("yyyy年M月d日 EEEE", Locale.CHINA) } private val timeFormat by lazy { SimpleDateFormat("HH:mm:ss", Locale.CHINA) } fun getChineseDateTimePair(date: Date = Date()): Pair { return dateFormat.format(date) to timeFormat.format(date) } /** * 实时时间流(每秒更新) * @param intervalMillis 更新间隔(默认1秒) */ fun realTimeChineseDateFlow(intervalMillis: Long = 1000) = flow { while (true) { emit(getChineseDateTimeString()) delay(intervalMillis) } } /** * 解析日期时间字符串 * @param timeString 格式为 "yyyy-MM-dd HH:mm:ss" 的字符串 * @return Date 对象,解析失败返回 null */ fun parseDateTime(timeString: String?): Date? { return try { if (timeString == null) return null val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) format.parse(timeString) } catch (e: Exception) { // e.printStackTrace() Timber.e(e.message) null } } /** * 判断给定时间是否距离当前时间超过72小时 * @param timeInMillis 时间戳(毫秒) * @return true 表示超过72小时,false 表示未超过 */ fun isMoreThanHoursFromNow(timeInMillis: Long): Boolean { val currentTime = System.currentTimeMillis() val timeDifference = currentTime - timeInMillis val hoursDifference = timeDifference / (1000 * 60 * 60) // 毫秒转小时 return hoursDifference >= 72 } /** * 获取时间间隔描述 */ fun getTimeAgo(date: Date?): String { if (date == null) return "未知时间" val now = Date() val diffMillis = now.time - date.time // 如果是未来时间 if (diffMillis < 0) { val futureHours = abs(diffMillis) / (1000 * 60 * 60) return if (futureHours < 24) { "未来 $futureHours 小时" } else { val days = futureHours / 24 "未来 $days 天" } } // 过去时间 val hours = diffMillis / (1000 * 60 * 60) return when { hours < 1 -> "刚刚" hours < 24 -> "${hours}小时前" else -> { val days = hours / 24 "${days}天前" } } } }