Parse ISO 8601 time duration using Go (for instance PT90M)
Asked Answered
S

2

9

Is there any easy way to convert an ISO 8601 string time duration (P(n)Y(n)M(n)DT(n)H(n)M(n)S) to time.Duration?

From Wikipedia on ISO 8601 durations:

For example, "P3Y6M4DT12H30M5S" represents a duration of "three years, six months, four days, twelve hours, thirty minutes, and five seconds".

Suchta answered 3/11, 2020 at 21:28 Comment(3)
Parsing date/time strings is very well documented in Go. What have you tried? What problems did you encounter?Cultivation
This question is particularly about ISO 8601 duration that is not supported in std lib.Heiress
KeyB0rys, here is an example play.golang.org/p/guybDGoJVrT with 3rd party lib.Heiress
H
8

There is no API in standard library for that, but there is a 3rd party library that can add ISO 8601 duration to a time.Time: https://godoc.org/github.com/senseyeio/duration#Duration.Shift.

ISO 8601 duration can not be generally converted to a time.Duration because it depends on the base time.Time.

https://play.golang.org/p/guybDGoJVrT

package main

import (
    "fmt"
    "time"

    "github.com/senseyeio/duration"
)

func main() {
    d, _ := duration.ParseISO8601("P1D")
    today := time.Now()
    tomorrow := d.Shift(today)
    fmt.Println(today.Format("Jan _2"))    // Nov 11
    fmt.Println(tomorrow.Format("Jan _2")) // Nov 12
}
Heiress answered 3/11, 2020 at 21:55 Comment(1)
The issue here is it doesn't give you an actual time.Duration. It has it however it's not exported.Overarm
M
2

Finding existing solutions less than satisfactory I created my own module to parse ISO 8601 durations and convert them directly to a time.Duration. I hope you find it useful. :)

example usage: https://go.dev/play/p/Nz5akjy1c6W

Mime answered 24/1, 2022 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.