utils_test.go
2.6 KB
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
package utils
import (
"fmt"
"github.com/stretchr/testify/assert"
"testing"
"time"
)
func TestTimeSpan(t *testing.T) {
inputs := []struct {
t string
e bool
}{
{"10:00", false},
{"10:11", false},
{"24:00", true},
{"-1:00", true},
{"10:60", true},
{"A:B", true},
}
for i := range inputs {
err := ValidWorkTime(inputs[i].t)
if inputs[i].e {
assert.NotNil(t, err)
} else {
assert.Nil(t, err)
}
}
}
func TestComputeTimeDuration(t *testing.T) {
assertDuration := func(s string) time.Duration {
t, _ := time.ParseDuration(s)
return t
}
inputs := []struct {
t1 string
t2 string
ts time.Duration
}{
{
"9:00", "18:00", assertDuration("9h"),
},
{
"23:00", "6:00", assertDuration("7h"),
},
}
for i := range inputs {
input := inputs[i]
out, err := ComputeTimeDuration(input.t1, input.t2)
assert.Nil(t, err)
assert.Equal(t, input.ts, out)
}
}
const TIME_LAYOUT = "2006-01-02 03:04:05"
func TestTimeParse(t *testing.T) {
timeParse()
}
func timeParse() {
fmt.Println("0. now: ", time.Now())
str := "2018-09-10 10:00:00"
fmt.Println("1. str: ", str)
t, _ := time.Parse(TIME_LAYOUT, str)
fmt.Println("2. Parse time: ", t)
tStr := t.Format(TIME_LAYOUT)
fmt.Println("3. Format time str: ", tStr)
name, offset := t.Zone()
name2, offset2 := t.Local().Zone()
fmt.Printf("4. Zone name: %v, Zone offset: %v\n", name, offset)
fmt.Printf("5. Local Zone name: %v, Local Zone offset: %v\n", name2, offset2)
tLocal := t.Local()
tUTC := t.UTC()
fmt.Printf("6. t: %v, Local: %v, UTC: %v\n", t, tLocal, tUTC)
fmt.Printf("7. t: %v, Local: %v, UTC: %v\n", t.Format(TIME_LAYOUT), tLocal.Format(TIME_LAYOUT), tUTC.Format(TIME_LAYOUT))
fmt.Printf("8. Local.Unix: %v, UTC.Unix: %v\n", tLocal.Unix(), tUTC.Unix())
str2 := "1969-12-31 23:59:59"
t2, _ := time.Parse(TIME_LAYOUT, str2)
fmt.Printf("9. str2:%v,time: %v, Unix: %v\n", str2, t2, t2.Unix())
fmt.Printf("10. %v, %v\n", tLocal.Format(time.ANSIC), tUTC.Format(time.ANSIC))
fmt.Printf("11. %v, %v\n", tLocal.Format(time.RFC822), tUTC.Format(time.RFC822))
fmt.Printf("12. %v, %v\n", tLocal.Format(time.RFC822Z), tUTC.Format(time.RFC822Z))
//指定时区
parseWithLocation("America/Cordoba", str)
parseWithLocation("Asia/Shanghai", str)
parseWithLocation("Asia/Beijing", str)
}
func parseWithLocation(name string, timeStr string) (time.Time, error) {
locationName := name
if l, err := time.LoadLocation(locationName); err != nil {
println(err.Error())
return time.Time{}, err
} else {
lt, _ := time.ParseInLocation(TIME_LAYOUT, timeStr, l)
fmt.Println(locationName, lt)
return lt, nil
}
}