Compare And Sort Time Instants

time.Time.Compare returns a three-way result that sorts directly, while Before and After answer boolean questions; ties are resolved by service name.

GoData Integrity

Code

gosnippet
38 lines
package main

import (
	"cmp"
	"fmt"
	"slices"
	"time"
)

type Deployment struct {
	Service string
	At      time.Time
}

func main() {
	base := time.Date(2026, 11, 14, 9, 0, 0, 0, time.UTC)
	deploys := []Deployment{
		{Service: "billing", At: base.Add(90 * time.Minute)},
		{Service: "auth", At: base},
		{Service: "orders", At: base.Add(-30 * time.Minute)},
		{Service: "search", At: base.Add(90 * time.Minute)},
	}

	// Before/After 只回答布尔问题
	fmt.Println("orders before auth:", deploys[2].At.Before(deploys[1].At))

	// Compare 给出三值结果:可直接喂给排序,平局按服务名仲裁
	slices.SortFunc(deploys, func(a, b Deployment) int {
		if c := a.At.Compare(b.At); c != 0 {
			return c
		}
		return cmp.Compare(a.Service, b.Service)
	})

	for _, d := range deploys {
		fmt.Println(d.At.Format(time.Kitchen), d.Service)
	}
}

Inside the snippet

Compare And Sort Time Instants is built around the function main.

Repetition is confined to for _, d := range deploys — the rest of the file is straight-line.

Putting it to use

The demo output is labeled (orders before auth:), so the output doubles as a step-by-step trace of what the file did.

Core lines

for _, d := range deploys {
fmt.Println(d.At.Format(time.Kitchen), d.Service)
}
return cmp.Compare(a.Service, b.Service)

Interactive Tools for This Topic

FAQ

What does Compare And Sort Time Instants print when run?
The script runs standalone; its 1 labeled outputs include `orders before auth:`.