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

Viewed 2282

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".

2 Answers

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
}
Related