feat: 支持通过 timer.CalcNextTimeWithRefer 计算下一个整点时间

This commit is contained in:
kercylan98 2023-07-18 18:25:21 +08:00
parent 28c6097044
commit 8835e4a88b
1 changed files with 20 additions and 0 deletions

View File

@ -17,3 +17,23 @@ func CalcNextSecWithTime(t time.Time, sec int) int {
next := now + int64(sec) - now%int64(sec) next := now + int64(sec) - now%int64(sec)
return int(next - now) return int(next - now)
} }
// CalcNextTimeWithRefer 根据参考时间计算下一个整点时间
// - 假设当 now 为 14:15:16 参考时间为 10 分钟, 则返回 14:20:00
// - 假设当 now 为 14:15:16 参考时间为 20 分钟, 则返回 14:20:00
//
// 当 refer 小于 1 分钟时,将会返回当前时间
func CalcNextTimeWithRefer(now time.Time, refer time.Duration) time.Time {
referInSeconds := int(refer.Minutes()) * 60
if referInSeconds <= 0 {
return now
}
minutes := now.Minute()
seconds := now.Second()
remainder := referInSeconds - (minutes*60+seconds)%referInSeconds
nextTime := now.Add(time.Duration(remainder) * time.Second)
nextTime = time.Date(nextTime.Year(), nextTime.Month(), nextTime.Day(), nextTime.Hour(), nextTime.Minute(), 0, 0, nextTime.Location())
return nextTime
}