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".
What is an ISO 8601 duration? ISO 8601 is a set of standardized date and time formats in an attempt to tame every programmer's favorite challenge. Durations represent the amount of time between two dates or times. You can leave certain intervals off if they don't apply, but you must include the T before any time intervals ( P<date>T<time> ).
It is commonly used to represent dates and times in code (e.g. Date.toISOString ). There is one less known specification in this standard related to duration. What is duration standard? Duration defines the interval in time and is represented by the following format: Letters P and T represent, respectively, makers for period and time blocks.
Duration defines the interval in time and is represented by the following format: Letters P and T represent, respectively, makers for period and time blocks. The capitals letters Y, M, W, D, H, M, S represent the segments in order: years, months, weeks, days, hours, minutes, and seconds.
RFC3339 is equivalent to ISO 8601. Specifically, it has identical format, RFC3339 just has stricter requirements (example, it requires a complete date representation with 4-digit year). What's the difference between ISO 8601 and RFC 3339 Date Formats? So you can use the constant time.RFC3339 as your layout.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With