Given a date, we’re looking at how you can add a duration to it, like a month or two, but ignoring weekends. This is usually most used for businesses focused on working-days - but it could easily be adapted to do the opposite, only weekends. It’s built around the standard lib time package so no extra packages needed.
We’ve got some example code below that makes a date and adds on 14 days, while skipping the weekend days out. We are doing this manually just checking each day on the Weekday() function and comparing it to time.Saturday or time.Sunday.
packagemainimport("fmt""time")funcmain(){// Build Start
start:=time.Date(2023,6,8,0,0,0,0,time.UTC)fmt.Println("Start Date:",start.Format("2006-01-02"))// Run Ignore Weekends
duration:=14// 2 weeks duration
end:=addDaysIgnoreWeekends(start,duration)fmt.Println("End Date (skipping weekends):",end.Format("2006-01-02"))}funcaddDaysIgnoreWeekends(starttime.Time,daysint)time.Time{fori:=0;i<days;{start=start.Add(24*time.Hour)// if the day is Saturday or Sunday, continue to the next day without counting it
ifstart.Weekday()!=time.Saturday&&start.Weekday()!=time.Sunday{i++}}returnstart}
Most of the logic will be handled inside addDaysIgnoreWeekends() as it steps through each day. Therefore this function could also easily be adapted to ignore bank-holidays and generic/religous holidays like christmas.
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.