Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 783
KeyB0rys Avatar asked Nov 03 '20 21:11

KeyB0rys


People also ask

What is an ISO 8601 duration?

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

What is the use of toisostring duration?

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.

What is the format for duration?

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.

What's the difference between ISO 8601 and RFC 3339 date formats?

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.


1 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
}
like image 103
vearutop Avatar answered Oct 18 '22 16:10

vearutop