How to Ignore Weekends in Go

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
	"fmt"
	"time"
)

func main() {

	// 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"))
}

func addDaysIgnoreWeekends(start time.Time, days int) time.Time {
	for i := 0; i < days; {
		start = start.Add(24 * time.Hour)
		// if the day is Saturday or Sunday, continue to the next day without counting it
		if start.Weekday() != time.Saturday && start.Weekday() != time.Sunday {
			i++
		}
	}
	return start
}

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.

ignore weekends in go