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

Grokify
  • 15,092
  • 6
  • 60
  • 81
KeyB0rys
  • 392
  • 5
  • 13

2 Answers2

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
}
vearutop
  • 3,924
  • 24
  • 41
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

SimplySerenity
  • 125
  • 1
  • 8