package timer import ( "fmt" "time" ) // TimeInterval 计算两个时间的间隔,超过24小时返回天数,否则返回几小时前 func TimeInterval(targetTime time.Time) string { // 1. 将当前时间和目标时间统一转换为本地时区(time.Local) now := time.Now().In(time.Local) // 当前时间转为本地时区 target := targetTime.In(time.Local) // 目标时间转为本地时区 // 2. 计算时间差(取绝对值,避免因目标时间在未来导致负数) var diff time.Duration if now.After(target) { diff = now.Sub(target) } else { diff = target.Sub(now) } // 3. 转换为总小时数(取整数部分,自动截断小数) // 转换为总分钟数(取整数部分,自动截断秒数) totalMinutes := int(diff.Minutes()) // 按不同阈值返回对应格式 switch { case totalMinutes >= 24*60: // 24小时 = 1440分钟 days := totalMinutes / (24 * 60) return fmt.Sprintf("%d天前", days) case totalMinutes >= 60: // 1小时 = 60分钟 hours := totalMinutes / 60 return fmt.Sprintf("%d小时前", hours) case totalMinutes < 1: return "刚刚" default: // 不足1小时 return fmt.Sprintf("%d分钟前", totalMinutes) } } // GetZeroTime 获取当天零点时间 func GetZeroTime() time.Time { now := time.Now() // 2. 使用当天的年月日,将时分秒纳秒设为0,并保留原时区(Location) zeroTime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local) return zeroTime }