79 lines
2.4 KiB
Go
79 lines
2.4 KiB
Go
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
|
|
}
|
|
|
|
// GetMaxTime 获取当天最大时间
|
|
func GetMaxTime() time.Time {
|
|
now := time.Now()
|
|
// 2. 使用当天的年月日,将时分秒纳秒设为0,并保留原时区(Location)
|
|
maxTime := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 999999999, time.Local)
|
|
return maxTime
|
|
}
|
|
|
|
// ParseDateRange 解析日期范围,未传则默认最近30天
|
|
func ParseDateRange(startDate, endDate string) (time.Time, time.Time) {
|
|
now := time.Now()
|
|
layout := "2006-01-02"
|
|
|
|
end, err := time.Parse(layout, endDate)
|
|
if err != nil {
|
|
end = now
|
|
}
|
|
// 结束日期取当天 23:59:59
|
|
end = time.Date(end.Year(), end.Month(), end.Day(), 23, 59, 59, 0, time.Local)
|
|
|
|
start, err := time.Parse(layout, startDate)
|
|
if err != nil {
|
|
start = end.AddDate(0, 0, -29) // 默认30天
|
|
}
|
|
// 开始日期取当天 00:00:00
|
|
start = time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, time.Local)
|
|
|
|
return start, end
|
|
}
|