英文:
Check if date is a recurrence of another day
问题
如何检查一个日期是否是另一个日期的双周(每两周一次)重复?例如,对于初始日期13/01/2022,如何检查日期31/03/2022是否是初始日期的双周重复?
英文:
How can i check if a date is a biweekly(every two weeks) recurrence of another?
For instance for the initial date 13/01/2022, how can i check if the date 31/03/2022 is a biweekly recurrence of the initial date?
答案1
得分: 1
SameDay
函数用于检查两个时间是否在同一天的时间段内。对于双周,使用间隔为14。(这假设一个“天”是指当地时间,但你可以将time.Local
更改为UTC或任何时区。)请注意,86400是一天的秒数。
import (
"time"
)
const (
SecondsPerDay = 24*60*60
)
func main() {
println(SameDay(14, time.Now(), time.Now().Add(time.Hour*24*14)))
println(SameDay(14, time.Now(), time.Now().Add(time.Hour*24*15)))
}
// StartOfDay找到当地时区的一天的开始时间
func StartOfDay(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
}
// SameDay如果两个时间在间隔的同一天上,则返回true
// interval = 时间间隔(以天为单位)
// t1, t2 = 两个时间
func SameDay(interval int, t1, t2 time.Time) bool {
return (StartOfDay(t1).Unix()/SecondsPerDay)%interval == (StartOfDay(t2).Unix()/SecondsPerDay)%interval
}
英文:
The SameDay
function checks if two times fall on the same day of a time period. Use an interval of 14 for biweekly. (This assumes a "day" in local time but you can change time.Local
to be UTC or any timezone.) Note that 86400 is seconds in a day.
import (
"time"
)
const (
SecondsPerDay = 24*60*60
)
func main() {
println(SameDay(14, time.Now(), time.Now().Add(time.Hour*24*14)))
println(SameDay(14, time.Now(), time.Now().Add(time.Hour*24*15)))
}
// StartOfDay finds time of start of day in local time zone
func StartOfDay(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
}
// SameDay returns true if times fall on the same day of an interval
// interval = the time interval in days
// t1, t2 = the two times
func SameDay(interval int, t1, t2 time.Time) bool {
return (StartOfDay(t1).Unix()/SecondsPerDay)%interval == (StartOfDay(t2).Unix()/SecondsPerDay)%interval
}
答案2
得分: 0
另一种方法,
func isBiWeekly(t1, t2 time.Time) bool {
t1 = t1.Truncate(time.Hour)
t2 = t2.Truncate(time.Hour)
return int(t2.Sub(t1).Hours()/24)%14 == 0
}
完整版本:https://go.dev/play/p/da3Gliztb2B
英文:
another approach,
func isBiWeekly(t1, t2 time.Time) bool {
t1 = t1.Truncate(time.Hour)
t2 = t2.Truncate(time.Hour)
return int(t2.Sub(t1).Hours()/24)%14 == 0
}
full version : https://go.dev/play/p/da3Gliztb2B
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论