Skip to content

Business Day Calculator — Go source

Step N business days from a date or count the business days in a span — with your weekend definition (Sat-Sun, Fri-Sat, Sunday, none) and your holiday list. UTC dates, no DST traps; neighboring business days shown alongside.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package businessdaycalculator is the Go twin of CosmoDev's
// src/lib/business-days.ts (dual source: the web lib is TypeScript, the CLI
// lib is Go — kept in lock-step). Pure + deterministic, never panics. The
// table-driven tests in business-day-calculator_test.go share vectors with
// src/lib/business-days.test.ts so the two implementations are held to the
// same contract.
//
// Dates are YYYY-MM-DD strings read as UTC midnights — no DST traps,
// deterministic for the Go twin. Weekend days and holidays are INPUTS
// (defaults: Sat/Sun, none): callers wire their own holiday list. Every
// exported function mirrors its TS counterpart, and the TS null return maps
// to Go's ok=false (invalid or unparseable input yields the zero value).
package businessdaycalculator

import (
	"regexp"
	"strconv"
	"time"
)

// Options configures the business-day functions. The zero value (Options{})
// matches the TS defaults (weekendDays: [0, 6], holidays: none).
type Options struct {
	// WeekendDays are UTC weekday numbers off work; 0=Sunday … 6=Saturday.
	// nil means the TS default [0, 6]. A non-nil (even empty) slice replaces
	// the default entirely — exactly like the TS spread of an explicit array.
	WeekendDays []int
	// Holidays are holiday dates, YYYY-MM-DD. Entries that are not canonical
	// dates never match a normalized day and are simply inert.
	Holidays []string
}

// defaultWeekendDays mirrors DEFAULTS.weekendDays in the TS lib.
var defaultWeekendDays = []int{0, 6}

// isoDateShape accepts exactly YYYY-MM-DD (ASCII digits); real-month/real-day
// validation happens via the round-trip check in parseUtcDate.
var isoDateShape = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)

// parseUtcDate parses YYYY-MM-DD to a UTC midnight; ok is false on anything
// else — including rollover dates like 2026-13-01 or 2026-11-31 that Go's
// time package (like Date.UTC in the TS) would silently normalize.
func parseUtcDate(iso string) (time.Time, bool) {
	if !isoDateShape.MatchString(iso) {
		return time.Time{}, false
	}
	y, errY := strconv.Atoi(iso[0:4])
	mo, errM := strconv.Atoi(iso[5:7])
	d, errD := strconv.Atoi(iso[8:10])
	if errY != nil || errM != nil || errD != nil {
		return time.Time{}, false
	}
	t := time.Date(y, time.Month(mo), d, 0, 0, 0, 0, time.UTC)
	// Round-trip check: 2026-13-01 normalizes to 2027-01-01 and
	// 2026-11-31 to 2026-12-01, so the fields no longer round-trip.
	if t.Year() != y || t.Month() != time.Month(mo) || t.Day() != d {
		return time.Time{}, false
	}
	return t, true
}

// toIso formats a UTC midnight back to YYYY-MM-DD (TS toISOString().slice(0, 10)).
func toIso(d time.Time) string { return d.Format("2006-01-02") }

// resolveDefaults merges opts onto the TS DEFAULTS: nil WeekendDays → [0, 6].
// Holidays are compared directly, so a nil list simply means none. Mirrors
// `{ ...DEFAULTS, ...opts }`.
func resolveDefaults(opts Options) Options {
	if opts.WeekendDays == nil {
		opts.WeekendDays = defaultWeekendDays
	}
	return opts
}

// isOff reports whether day is a weekend or a holiday under o. Mirrors the TS
// isOff() helper.
func isOff(day time.Time, o Options) bool {
	wd := int(day.Weekday()) // time.Weekday() is 0=Sunday … 6=Saturday, like getUTCDay()
	for _, off := range o.WeekendDays {
		if off == wd {
			return true
		}
	}
	iso := toIso(day)
	for _, h := range o.Holidays {
		if h == iso {
			return true
		}
	}
	return false
}

// IsBusinessDay reports whether iso is a real date AND a working day. It is
// the Go twin of isBusinessDay() in the TS lib.
func IsBusinessDay(iso string, opts Options) bool {
	o := resolveDefaults(opts)
	d, ok := parseUtcDate(iso)
	return ok && !isOff(d, o)
}

// AddBusinessDays steps n working days from start (negative steps backward).
// n=0 rolls a non-business start onto the next business day in the step
// direction (−0 behaves as +0, like the TS Math.trunc logic); n=1 from a
// weekend is simply the following business day. Invalid → ok=false. It is
// the Go twin of addBusinessDays() in the TS lib.
func AddBusinessDays(start string, n int, opts Options) (string, bool) {
	o := resolveDefaults(opts)
	d, ok := parseUtcDate(start)
	if !ok {
		return "", false
	}

	step := 1
	if n < 0 {
		step = -1
	}
	steps := n
	if steps < 0 {
		steps = -steps // int is already truncation-safe, like Math.trunc
	}
	cur := d
	if steps == 0 {
		for isOff(cur, o) {
			cur = cur.AddDate(0, 0, step)
		}
		return toIso(cur), true
	}
	counted := 0
	for counted < steps {
		cur = cur.AddDate(0, 0, step)
		if !isOff(cur, o) {
			counted++
		}
	}
	return toIso(cur), true
}

// BusinessDaysBetween counts business days in [a, b) — half-open,
// chronological: if b precedes a the pair is swapped and counted over [b, a).
// Same-day input is 0. Invalid → ok=false. It is the Go twin of
// businessDaysBetween() in the TS lib.
func BusinessDaysBetween(a, b string, opts Options) (int, bool) {
	o := resolveDefaults(opts)
	da, okA := parseUtcDate(a)
	db, okB := parseUtcDate(b)
	if !okA || !okB {
		return 0, false
	}
	if da.After(db) {
		da, db = db, da
	}

	count := 0
	for d := da; d.Before(db); d = d.AddDate(0, 0, 1) {
		if !isOff(d, o) {
			count++
		}
	}
	return count, true
}

// NextBusinessDay returns the working day strictly after the date, as
// YYYY-MM-DD. Invalid → ok=false. It is the Go twin of nextBusinessDay() in
// the TS lib.
func NextBusinessDay(iso string, opts Options) (string, bool) {
	o := resolveDefaults(opts)
	d, ok := parseUtcDate(iso)
	if !ok {
		return "", false
	}
	next := d.AddDate(0, 0, 1)
	for isOff(next, o) {
		next = next.AddDate(0, 0, 1)
	}
	return toIso(next), true
}

// PreviousBusinessDay returns the working day strictly before the date, as
// YYYY-MM-DD. Invalid → ok=false. It is the Go twin of previousBusinessDay()
// in the TS lib.
func PreviousBusinessDay(iso string, opts Options) (string, bool) {
	o := resolveDefaults(opts)
	d, ok := parseUtcDate(iso)
	if !ok {
		return "", false
	}
	prev := d.AddDate(0, 0, -1)
	for isOff(prev, o) {
		prev = prev.AddDate(0, 0, -1)
	}
	return toIso(prev), true
}

Also available in 1 other language

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in several languages — the same contract, ported. Compare all languages side by side →