首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Golang解析time.Duration

Golang解析time.Duration
EN

Stack Overflow用户
提问于 2015-01-24 13:28:33
回答 2查看 21.2K关注 0票数 9

我想解析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持续时间

EN

回答 2

Stack Overflow用户

发布于 2015-06-02 09:25:09

它并不完全是“开箱即用”,但正则表达式可以完成以下工作:

代码语言:javascript
复制
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)
}
票数 3
EN

Stack Overflow用户

发布于 2019-08-22 22:49:16

下面是处理小数时间单位(如PT3.001S )的代码。

代码语言:javascript
复制
var durationRegex = regexp.MustCompile(`P([\d\.]+Y)?([\d\.]+M)?([\d\.]+D)?T?([\d\.]+H)?([\d\.]+M)?([\d\.]+?S)?`)

// ParseDuration converts a ISO8601 duration into a time.Duration
func ParseDuration(str string) time.Duration {
   matches := durationRegex.FindStringSubmatch(str)

   years := parseDurationPart(matches[1], time.Hour*24*365)
   months := parseDurationPart(matches[2], time.Hour*24*30)
   days := parseDurationPart(matches[3], time.Hour*24)
   hours := parseDurationPart(matches[4], time.Hour)
   minutes := parseDurationPart(matches[5], time.Second*60)
   seconds := parseDurationPart(matches[6], time.Second)

   return time.Duration(years + months + days + hours + minutes + seconds)
}

func parseDurationPart(value string, unit time.Duration) time.Duration {
   if len(value) != 0 {
       if parsed, err := strconv.ParseFloat(value[:len(value)-1], 64); err == nil {
           return time.Duration(float64(unit) * parsed)
       }
   }
   return 0
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28125963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档