From 8835e4a88bd80bb795a93dfe2494445d8acf0d95 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Tue, 18 Jul 2023 18:25:21 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E9=80=9A=E8=BF=87=20?= =?UTF-8?q?timer.CalcNextTimeWithRefer=20=E8=AE=A1=E7=AE=97=E4=B8=8B?= =?UTF-8?q?=E4=B8=80=E4=B8=AA=E6=95=B4=E7=82=B9=E6=97=B6=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/times/calc.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/utils/times/calc.go b/utils/times/calc.go index 83d6a87..ab693a9 100644 --- a/utils/times/calc.go +++ b/utils/times/calc.go @@ -17,3 +17,23 @@ func CalcNextSecWithTime(t time.Time, sec int) int { next := now + int64(sec) - now%int64(sec) 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 +}