...
1# duration
2
3[](https://pkg.go.dev/github.com/sosodev/duration)
4
5It's a Go module for parsing [ISO 8601 durations](https://en.wikipedia.org/wiki/ISO_8601#Durations) and converting them to the often much more useful `time.Duration`.
6
7## why?
8
9ISO 8601 is a pretty common standard and sometimes these durations show up in the wild.
10
11## installation
12
13`go get github.com/sosodev/duration`
14
15## [usage](https://go.dev/play/p/Nz5akjy1c6W)
16
17```go
18package main
19
20import (
21 "fmt"
22 "time"
23 "github.com/sosodev/duration"
24)
25
26func main() {
27 d, err := duration.Parse("P3Y6M4DT12H30M5.5S")
28 if err != nil {
29 panic(err)
30 }
31
32 fmt.Println(d.Years) // 3
33 fmt.Println(d.Months) // 6
34 fmt.Println(d.Days) // 4
35 fmt.Println(d.Hours) // 12
36 fmt.Println(d.Minutes) // 30
37 fmt.Println(d.Seconds) // 5.5
38
39 d, err = duration.Parse("T33.3S")
40 if err != nil {
41 panic(err)
42 }
43
44 fmt.Println(d.ToTimeDuration() == time.Second*33+time.Millisecond*300) // true
45}
46```
47
48## correctness
49
50This module aims to implement the ISO 8601 duration specification correctly. It properly supports fractional units and has unit tests
51that assert the correctness of it's parsing and conversion to a `time.Duration`.
52
53With that said durations with months or years specified will be converted to `time.Duration` with a little fuzziness. Since I
54couldn't find a standard value, and they obviously vary, for those I used `2.628e+15` nanoseconds for a month and `3.154e+16` nanoseconds for a year.
View as plain text