Skip to content

Timezone Meeting Planner — Go source

One explicit moment, every team timezone: wall-clock rows with weekday and UTC offset, a 9-to-17 business-hours window marker per zone, and the best next meeting starts ranked by how many teammates are awake for them.

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

// Package timezoneconverter is the Go twin of CosmoDev's src/lib/timezone.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
// timezone-converter_test.go share vectors with src/lib/timezone.test.ts so
// the two implementations are held to the same contract.
//
// Everything takes an EXPLICIT ISO instant — never the ambient clock — so the
// twin and its tests are deterministic across runtimes. The IANA tzdb is
// embedded via the time/tzdata blanket import, so zone lookups work
// hermetically even on hosts without a system zoneinfo directory.
//
// DIVERGENCE from the TS lib: Go has no Intl.supportedValuesOf, so
// ListTimeZones cannot enumerate the platform tzdb. It always returns the
// fixed FALLBACK_ZONES list from the TS lib (UTC guaranteed present,
// deduped, sorted) — the TS lib's old-runtime fallback path. Instant parsing
// is also stricter: Go requires RFC 3339 where new Date(...) tolerates more
// formats, and Go's LoadLocation accepts "Local"/"", which Intl rejects, so
// they are refused here for parity.
//
// Error mapping: the TS lib returns null for bad instants/zones; this twin
// returns an error instead.
package timezoneconverter

import (
	"fmt"
	"math"
	"sort"
	"time"

	_ "time/tzdata" // embed the IANA tzdb so LoadLocation works hermetically
)

// FallbackZones mirrors FALLBACK_ZONES in src/lib/timezone.ts: the fixed
// common-zone list used when the platform cannot enumerate its tzdb. The Go
// twin ALWAYS uses this list (see the package comment). Treat as read-only.
var FallbackZones = []string{
	"UTC",
	"America/Los_Angeles",
	"America/Denver",
	"America/Chicago",
	"America/New_York",
	"America/Sao_Paulo",
	"Europe/London",
	"Europe/Paris",
	"Europe/Berlin",
	"Europe/Moscow",
	"Africa/Cairo",
	"Africa/Lagos",
	"Africa/Johannesburg",
	"Asia/Dubai",
	"Asia/Karachi",
	"Asia/Kolkata",
	"Asia/Dhaka",
	"Asia/Bangkok",
	"Asia/Shanghai",
	"Asia/Singapore",
	"Asia/Hong_Kong",
	"Asia/Tokyo",
	"Asia/Seoul",
	"Australia/Sydney",
	"Pacific/Auckland",
}

// isoMillis is the layout of Date.prototype.toISOString():
// YYYY-MM-DDTHH:mm:ss.sssZ. Used so emitted slot ISO strings re-parse
// identically in both twins.
const isoMillis = "2006-01-02T15:04:05.000Z07:00"

// parseInstant mirrors new Date(iso): the instant, or an error for
// unparseable input. Go requires RFC 3339 here (see the package comment).
func parseInstant(iso string) (time.Time, error) {
	t, err := time.Parse(time.RFC3339, iso)
	if err != nil {
		return time.Time{}, fmt.Errorf("invalid ISO instant %q", iso)
	}
	return t, nil
}

// loadZone mirrors Intl.DateTimeFormat's timeZone validation: only real IANA
// ids are accepted. Go's time.LoadLocation additionally accepts "Local" and
// "", which Intl treats as invalid — refused here for parity.
func loadZone(zone string) (*time.Location, error) {
	if zone == "" || zone == "Local" {
		return nil, fmt.Errorf("unknown time zone %q", zone)
	}
	loc, err := time.LoadLocation(zone)
	if err != nil {
		return nil, fmt.Errorf("unknown time zone %q", zone)
	}
	return loc, nil
}

// zoneInfoAt builds the ZoneInfoResult for a loaded zone at an instant. The
// offset comes from the zone's rule at that instant (seconds east of UTC),
// rounded to whole minutes exactly like the TS lib's Date.UTC round-trip.
func zoneInfoAt(t time.Time, loc *time.Location, zone string) ZoneInfoResult {
	local := t.In(loc)
	_, offSec := local.Zone()
	offMin := int(math.Round(float64(offSec) / 60))
	abs := offMin
	sign := "+"
	if abs < 0 {
		sign = "-"
		abs = -abs
	}
	return ZoneInfoResult{
		Zone:          zone,
		Time:          local.Format("15:04"),
		Date:          local.Format("2006-01-02"),
		Weekday:       local.Format("Monday"), // Go renders long English names
		Offset:        fmt.Sprintf("%s%02d:%02d", sign, abs/60, abs%60),
		OffsetMinutes: offMin,
	}
}

// ZoneInfoResult is the wall-clock snapshot of one zone at an instant. It
// mirrors the ZoneInfo interface in the TS lib (the type is suffixed Result
// because Go cannot declare a type and a function with the same name — the
// function keeps the TS API name below).
type ZoneInfoResult struct {
	Zone          string // IANA zone id, as passed in
	Time          string // local wall clock, HH:mm (24h)
	Date          string // local date, YYYY-MM-DD
	Weekday       string // long English weekday name
	Offset        string // offset from UTC, +HH:MM / -HH:MM
	OffsetMinutes int    // offset from UTC in minutes (east positive)
}

// ZoneInfo reports wall-clock info for one zone at an ISO instant. It is the
// Go twin of zoneInfo() in src/lib/timezone.ts: invalid instants and unknown
// zones return an error where the TS lib returns null.
func ZoneInfo(iso, zone string) (ZoneInfoResult, error) {
	t, err := parseInstant(iso)
	if err != nil {
		return ZoneInfoResult{}, err
	}
	loc, err := loadZone(zone)
	if err != nil {
		return ZoneInfoResult{}, err
	}
	return zoneInfoAt(t, loc, zone), nil
}

// ListTimeZones returns all supported zone ids. It is the Go twin of
// listTimeZones() in src/lib/timezone.ts. DIVERGENCE (see the package
// comment): Go has no Intl.supportedValuesOf, so the platform tzdb cannot be
// enumerated — the fixed FallbackZones list is always returned (UTC
// guaranteed present, deduped, sorted), matching the TS lib's fallback path.
func ListTimeZones() []string {
	zones := make([]string, len(FallbackZones), len(FallbackZones)+1)
	copy(zones, FallbackZones)
	hasUTC := false
	for _, z := range zones {
		if z == "UTC" {
			hasUTC = true
			break
		}
	}
	if !hasUTC {
		zones = append(zones, "UTC")
	}
	sort.Strings(zones)
	return zones
}

// Window is the local business-hours window: inclusive start hour, exclusive
// end hour. Mirrors MeetingWindow in the TS lib.
type Window struct {
	Start int
	End   int
}

// Default window, matching the TS default { start: 9, end: 17 }.
const (
	DefaultWindowStart = 9
	DefaultWindowEnd   = 17
)

// ZoneStatus is one zone's feasibility at an instant. Mirrors ZoneStatus in
// the TS lib.
type ZoneStatus struct {
	Zone     string
	Hour     int    // local hour 0..23 at the instant
	Time     string // local wall clock, HH:mm
	InWindow bool
}

// MeetingPlanResult is meeting feasibility at an instant across zones. It
// mirrors the MeetingPlan interface in the TS lib (suffixed Result because
// Go cannot declare a type and a function with the same name — the function
// keeps the TS API name below).
type MeetingPlanResult struct {
	Instant       string       // the ISO instant, verbatim as passed
	Window        Window       // the window actually applied
	Zones         []ZoneStatus // invalid zones dropped, input order kept
	InWindowCount int
	Score         float64 // fraction of zones inside the window, 0..1
}

// planAt evaluates the window across zones at an instant. Invalid zones are
// dropped (not fatal); an empty or all-invalid zone list scores 0.
func planAt(iso string, t time.Time, zones []string, w Window) MeetingPlanResult {
	statuses := make([]ZoneStatus, 0, len(zones))
	for _, zone := range zones {
		loc, err := loadZone(zone)
		if err != nil {
			continue // invalid zone: dropped, not fatal
		}
		local := t.In(loc)
		hour := local.Hour()
		statuses = append(statuses, ZoneStatus{
			Zone:     zone,
			Hour:     hour,
			Time:     local.Format("15:04"),
			InWindow: hour >= w.Start && hour < w.End,
		})
	}
	inCount := 0
	for _, s := range statuses {
		if s.InWindow {
			inCount++
		}
	}
	score := 0.0
	if len(statuses) > 0 {
		score = float64(inCount) / float64(len(statuses))
	}
	return MeetingPlanResult{
		Instant:       iso,
		Window:        w,
		Zones:         statuses,
		InWindowCount: inCount,
		Score:         score,
	}
}

// MeetingPlan reports which zones sit inside local business hours at an ISO
// instant. It is the Go twin of meetingPlan() in src/lib/timezone.ts; pass
// DefaultWindowStart/DefaultWindowEnd for the TS default 9→17. Invalid
// instants return an error where the TS lib returns null; invalid zones are
// dropped instead of failing.
func MeetingPlan(iso string, zones []string, start, end int) (MeetingPlanResult, error) {
	t, err := parseInstant(iso)
	if err != nil {
		return MeetingPlanResult{}, err
	}
	return planAt(iso, t, zones, Window{Start: start, End: end}), nil
}

// SlotSuggestion is one ranked meeting start. Mirrors SlotSuggestion in the
// TS lib.
type SlotSuggestion struct {
	ISO           string // slot start, toISOString() form
	InWindowCount int
	Score         float64
}

// SuggestSlots scans forward hourly from the instant for the best meeting
// starts, returning up to count suggestions sorted by score desc, then
// earliest. It is the Go twin of suggestSlots() in src/lib/timezone.ts
// (TS defaults: count 3, 24h horizon — pass those explicitly). Invalid
// instants return an error where the TS lib returns [].
func SuggestSlots(iso string, zones []string, w Window, count, hours int) ([]SlotSuggestion, error) {
	start, err := parseInstant(iso)
	if err != nil {
		return nil, err
	}
	var slots []SlotSuggestion
	for h := 0; h < hours; h++ {
		at := start.Add(time.Duration(h) * time.Hour)
		// The slot ISO always re-parses, so the plan here is never nil.
		plan := planAt(at.UTC().Format(isoMillis), at, zones, w)
		if len(plan.Zones) == 0 {
			continue
		}
		slots = append(slots, SlotSuggestion{
			ISO:           at.UTC().Format(isoMillis),
			InWindowCount: plan.InWindowCount,
			Score:         plan.Score,
		})
	}
	sort.SliceStable(slots, func(i, j int) bool {
		if slots[i].Score != slots[j].Score {
			return slots[i].Score > slots[j].Score
		}
		return slots[i].ISO < slots[j].ISO
	})
	if count < 0 {
		count = 0
	}
	if count < len(slots) {
		slots = slots[:count]
	}
	return slots, nil
}

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 →