Home > Software design >  Check if date is a recurrence of another day
Check if date is a recurrence of another day

Time:06-12

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?

CodePudding user response:

I haven't tested it thoroughly but this might work to find if two times fall one the same biweekly day. (This assumes a "day" in local time.) Note that 86400 is seconds in a day, 14 is days in a week.


import (
    "time"
)

func main() {
    println(SameDayOfFortnight(time.Now(), time.Now().Add(time.Hour*24*14)))
    println(SameDayOfFortnight(time.Now(), time.Now().Add(time.Hour*24*15)))
}

// StartOfDay finds time of start of day
func StartOfDay(t time.Time) time.Time {
    return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
}

// SameDayOfFortnight returns true if two time fall on the same b-weekly day (in local time zone)
func SameDayOfFortnight(t1, t2 time.Time) bool {
    return (StartOfDay(t1).Unix()/86400) == (StartOfDay(t2).Unix()/86400)
}

Try it on the Go playground

CodePudding user response:

another approach,

func isBiWeekly(t1, t2 time.Time) bool {
    t1 = t1.Truncate(time.Hour * 24)
    t2 = t2.Truncate(time.Hour * 24)
    return int(t2.Sub(t1).Hours()/24) == 0
}

full version : https://go.dev/play/p/x5oU-V1YeLP

  • Related