使用 Go 解析 ISO 8601 持续时间(例如 PT90M)

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

有什么简单的方法可以将 ISO 8601 字符串持续时间 (P(n)Y(n)M(n)DT(n)H(n)M(n)S) 转换为 time.Duration

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

标准库中没有 API,但是有一个第三方库可以将 ISO 8601 持续时间添加到 time.Timehttps://godoc.org/github.com/senseyeio/duration#Duration.Shift.

ISO 8601 持续时间通常不能转换为 time.Duration,因为它取决于基础 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
}

发现现有的解决方案不太令人满意我创建了 my own module 来解析 ISO 8601 持续时间并将它们直接转换为 time.Duration。希望对你有帮助。 :)

用法示例:https://go.dev/play/p/Nz5akjy1c6W