-
Notifications
You must be signed in to change notification settings - Fork 0
/
funcs.go
105 lines (88 loc) · 1.76 KB
/
funcs.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"fmt"
"strings"
"text/template"
"time"
)
var GlobalFuncMap = template.FuncMap{
"duration": Duration,
"duration_number": DurationNumber,
"duration_dimension": DurationDimension,
}
func Duration(d time.Duration) string {
var sb strings.Builder
sign := ""
if d < 0 {
sign = "-"
d = -d
}
second := time.Second
minute := time.Minute
hour := time.Hour
day := 24 * hour
week := 7 * day
if weeks := d / week; weeks > 0 {
fmt.Fprintf(&sb, " %d weeks", weeks)
d /= week
}
if days := d / day; days > 0 {
fmt.Fprintf(&sb, " %d days", days)
d /= day
}
if hours := d / hour; hours > 0 {
fmt.Fprintf(&sb, " %dh", hours)
d /= hour
}
if minutes := d / minute; minutes > 0 {
fmt.Fprintf(&sb, " %dm", minutes)
d /= minute
}
if seconds := d / second; seconds > 0 {
fmt.Fprintf(&sb, " %ds", seconds)
// d /= second
}
return sign + sb.String()[1:]
}
func DurationNumberAndDimension(d time.Duration) (int, string) {
second := time.Second
minute := time.Minute
hour := time.Hour
day := 24 * hour
week := 7 * day
weeks := int(d / week)
if weeks > 0 {
return weeks, "w"
}
days := int(d / day)
if days > 0 {
return days, "d"
}
hours := int(d / hour)
if hours > 0 {
return hours, "h"
}
minutes := int(d / minute)
if minutes > 0 {
return minutes, "m"
}
seconds := int(d / second)
return seconds, "s"
}
func DurationNumber(d time.Duration) int {
num, _ := DurationNumberAndDimension(d)
return num
}
func DurationDimension(d time.Duration) string {
_, dim := DurationNumberAndDimension(d)
return dim
}
func PeriodStrToDuration(s string) time.Duration {
return map[string]time.Duration{
"s": time.Second,
"m": time.Minute,
"h": time.Hour,
"d": time.Hour * 24,
"w": time.Hour * 24 * 7,
}[s]
}