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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
FAQ
- What does Compare And Sort Time Instants print when run?
- The script runs standalone; its 1 labeled outputs include `orders before auth:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.