解析 – Golang解析时间.持续时间
发布时间:2020-12-16 19:04:35 所属栏目:大数据 来源:网络整理
导读:我想解析时间.Duration.持续时间是“PT15M”(字符串/字节),并希望将其转换为有效的时间.持续时间. 如果这是一个time.Time事情,我会用: t,错误:= time.Parse(time.RFC3339Nano,“2013-06-05T14:10:43.678Z”) 但这不存在(ParseDuration只接受一个参数):
我想解析时间.Duration.持续时间是“PT15M”(字符串/字节),并希望将其转换为有效的时间.持续时间.
如果这是一个time.Time事情,我会用: t,错误:= time.Parse(time.RFC3339Nano,“2013-06-05T14:10:43.678Z”) 但这不存在(ParseDuration只接受一个参数): d,错误:= time.ParseDuration(time.RFC3339Nano,“PT15M”) 我该如何解析这个ISO 8601 duration?
它并非完全“开箱即用”,但正则表达式完成了这项工作:
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) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |