猿问

Golang 解析 time.Duration

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


繁星coding
浏览 434回答 2
2回答

慕村9548890

它并不完全是“开箱即用”,而是正则表达式可以完成这项工作:package mainimport "fmt"import "regexp"import "strconv"import "time"func main() {&nbsp; &nbsp; fmt.Println(ParseDuration("PT15M"))&nbsp; &nbsp; fmt.Println(ParseDuration("P12Y4MT15M"))}func ParseDuration(str string) time.Duration {&nbsp; &nbsp; 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)?`)&nbsp; &nbsp; matches := durationRegex.FindStringSubmatch(str)&nbsp; &nbsp; years := ParseInt64(matches[1])&nbsp; &nbsp; months := ParseInt64(matches[2])&nbsp; &nbsp; days := ParseInt64(matches[3])&nbsp; &nbsp; hours := ParseInt64(matches[4])&nbsp; &nbsp; minutes := ParseInt64(matches[5])&nbsp; &nbsp; seconds := ParseInt64(matches[6])&nbsp; &nbsp; hour := int64(time.Hour)&nbsp; &nbsp; minute := int64(time.Minute)&nbsp; &nbsp; second := int64(time.Second)&nbsp; &nbsp; 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 {&nbsp; &nbsp; if len(value) == 0 {&nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; }&nbsp; &nbsp; parsed, err := strconv.Atoi(value[:len(value)-1])&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; }&nbsp; &nbsp; return int64(parsed)}

交互式爱情

这是处理分数时间单位的代码,如PT3.001S.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.Durationfunc ParseDuration(str string) time.Duration {&nbsp; &nbsp;matches := durationRegex.FindStringSubmatch(str)&nbsp; &nbsp;years := parseDurationPart(matches[1], time.Hour*24*365)&nbsp; &nbsp;months := parseDurationPart(matches[2], time.Hour*24*30)&nbsp; &nbsp;days := parseDurationPart(matches[3], time.Hour*24)&nbsp; &nbsp;hours := parseDurationPart(matches[4], time.Hour)&nbsp; &nbsp;minutes := parseDurationPart(matches[5], time.Second*60)&nbsp; &nbsp;seconds := parseDurationPart(matches[6], time.Second)&nbsp; &nbsp;return time.Duration(years + months + days + hours + minutes + seconds)}func parseDurationPart(value string, unit time.Duration) time.Duration {&nbsp; &nbsp;if len(value) != 0 {&nbsp; &nbsp; &nbsp; &nbsp;if parsed, err := strconv.ParseFloat(value[:len(value)-1], 64); err == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return time.Duration(float64(unit) * parsed)&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}&nbsp; &nbsp;return 0}
随时随地看视频慕课网APP

相关分类

Go
我要回答