/
util.go
40 lines (36 loc) · 998 Bytes
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package cmd
import (
"bytes"
"regexp"
"strconv"
"time"
)
func write(buff *bytes.Buffer, str ...string) {
for _, s := range str {
buff.WriteString(s)
}
}
func parseISO8601(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)
}