A small, zero alloc and high performance libary for parsing ISO8601 compliant duration format into Go time compatible representation.
go get github.com/xnacly/go-iso8601-duration- ISO8601 duration parsing formats:
[+-]P[n]Y[n]W[n]M[n]DT[n]H[n]M[n]Sviagoiso8601duration.From:- aligned with ECMAScript: Temporal - 7 Temporal.Duration Objects and ISO8601
- Interop with
time.Timeandtime.Durationvia:goiso8601duration.Duration.Apply(time.Time) time.Timegoiso8601duration.Duration.Duration() time.Durationgoiso8601duration.FromDuration(time.Duration) goiso8601duration.Duration
- Serializing
goiso8601duration.Durationto the correct formatgoiso8601duration.Duration.String - JSON serialisation support via
json.Unmarshallerandjson.Marshaller - High quality errors with position context.
package main
import (
"fmt"
"time"
"github.com/xnacly/go-iso8601-duration"
)
func Must[T any](t T, err error) T {
if err != nil {
panic(err)
}
return t
}
func main() {
rawDuration := "PT1H30M12S"
duration := Must(goiso8601duration.From(rawDuration))
// 1h30m12s PT1H30M12S
fmt.Println(duration.Duration().String(), duration.String())
// 01:00:00 02:30:12
fmt.Println(
time.
Unix(0, 0).
Format(time.TimeOnly),
duration.
Apply(time.Unix(0, 0)).
Format(time.TimeOnly),
)
type arrival struct {
In goiso8601duration.Duration `json:"in"`
}
asJson := Must(
json.Marshal(
arrival{
In: goiso8601duration.FromDuration(
12*time.Minute + 43*time.Second,
),
},
),
)
// {"in":"PT12M43S"}
fmt.Println(string(asJson))
var a arrival
json.Unmarshal(asJson, &a)
// {In:PT12M43S}
fmt.Printf("%+v\n", a)
}Reproduce with:
goos: linux
goarch: amd64
pkg: github.com/xnacly/go-iso8601-duration
cpu: AMD Ryzen 7 3700X 8-Core Processor
BenchmarkDuration/P0D-16 120725466 9.931 ns/op 0 B/o 0 allocs/op
BenchmarkDuration/PT15H-16 92520681 11.67 ns/op 0 B/o 0 allocs/op
BenchmarkDuration/P1W-16 100000000 10.15 ns/op 0 B/o 0 allocs/op
BenchmarkDuration/P15W-16 100000000 10.26 ns/op 0 B/o 0 allocs/op
BenchmarkDuration/P1Y15W-16 82810779 14.83 ns/op 0 B/o 0 allocs/op
BenchmarkDuration/P15Y-16 120902158 10.29 ns/op 0 B/o 0 allocs/op
BenchmarkDuration/P15Y3M-16 75393909 15.68 ns/op 0 B/o 0 allocs/op
BenchmarkDuration/P15Y3M41D-16 56214748 22.31 ns/op 0 B/o 0 allocs/op
BenchmarkDuration/PT15M-16 91787005 12.85 ns/op 0 B/o 0 allocs/op
BenchmarkDuration/PT15M10S-16 53683030 19.45 ns/op 0 B/o 0 allocs/op
BenchmarkDuration/P3Y6M4DT12H30M5S-16 28636116 42.47 ns/op 0 B/op 0 allocs/op
PASS
ok github.com/xnacly/go-iso8601-duration 14.860s