Golang解析时间。持续时间

时间:2015-01-24 13:28:34

标签: parsing time go duration iso8601

我想解析time.Duration。持续时间为"PT15M"(字符串/字节),并希望将其转换为有效的time.Duration


如果这是time.Time,我会使用:

t, err := time.Parse(time.RFC3339Nano, "2013-06-05T14:10:43.678Z")

但这不存在(ParseDuration只接受一个参数):

d, err := time.ParseDuration(time.RFC3339Nano, "PT15M")


如何解析此ISO 8601 duration

2 个答案:

答案 0 :(得分:1)

它不完全是"开箱即用"但正则表达式可以完成这项工作:

package main

import "fmt"
import "regexp"
import "strconv"
import "time"

func main() {
    fmt.Println(ParseDuration("PT15M"))
    fmt.Println(ParseDuration("P12Y4MT15M"))
}

func ParseDuration(str string) time.Duration {
    durationRegex := regexp.MustCompile(`P(?P<years>\d+Y)?(?P<months>\d+M)?(?P<days>\d+D)?T?(?P<hours>\d+H)?(?P<minutes>\d+M)?(?P<seconds>\d+S)?`)
    matches := durationRegex.FindStringSubmatch(str)

    years := ParseInt64(matches[1])
    months := ParseInt64(matches[2])
    days := ParseInt64(matches[3])
    hours := ParseInt64(matches[4])
    minutes := ParseInt64(matches[5])
    seconds := ParseInt64(matches[6])

    hour := int64(time.Hour)
    minute := int64(time.Minute)
    second := int64(time.Second)
    return time.Duration(years*24*365*hour + months*30*24*hour + days*24*hour + hours*hour + minutes*minute + seconds*second)
}

func ParseInt64(value string) int64 {
    if len(value) == 0 {
        return 0
    }
    parsed, err := strconv.Atoi(value[:len(value)-1])
    if err != nil {
        return 0
    }
    return int64(parsed)
}

答案 1 :(得分:1)

这里是处理小数时间单位的代码,例如* { box-sizing: border-box; } .column { padding: 10px; margin: 5px; } .row:after { content: ""; display: table; clear: both; } .row { display: flex; flex-direction: row; align-items: flex-start; } .row div { display: flex; flex-direction: column; }

PT3.001S