检查日期是否是另一天的重复发生。

huangapple go评论90阅读模式
英文:

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
}

在Go Playground上试一试

英文:

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
}

Try it on the Go playground

答案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

huangapple
  • 本文由 发表于 2022年6月12日 20:41:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/72592290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定