-
Notifications
You must be signed in to change notification settings - Fork 2
/
ztime.go
130 lines (104 loc) · 2.38 KB
/
ztime.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package time
import (
"time"
"strings"
"strconv"
)
type Ztime struct {
time time.Time
err error
}
func (this *Ztime) Now() (*Ztime) {
this.time = time.Now()
return this
}
func (this *Ztime) SetLocation(timezone string) (*Ztime) {
if this.err != nil {
return this
}
t, err := time.LoadLocation(timezone)
if err != nil {
this.err = err
return this
}
this.time.In(t)
return this
}
//Format 设定时间格式
//兼容官方Format格式. 同时支持YYYY-MM-DD hh:mm:ss格式
/*
##### Example
```go
new(Ztime).Now().UTC().AddHour(7).Format("YYYY-MM-DDThh:mm")
```
*/
func (this *Ztime) Format(format string) (string, error) {
if strings.Contains(format, "YYYY") {
format = strings.Replace(format, "YYYY", "2006", -1)
}
if strings.Contains(format, "MM") {
format = strings.Replace(format, "MM", "01", -1)
}
if strings.Contains(format, "DD") {
format = strings.Replace(format, "DD", "02", -1)
}
if strings.Contains(format, "hh") {
format = strings.Replace(format, "hh", "15", -1)
}
if strings.Contains(format, "mm") {
format = strings.Replace(format, "mm", "04", -1)
}
if strings.Contains(format, "ss") {
format = strings.Replace(format, "ss", "05", -1)
}
return this.time.Format(format), this.err
}
func (this *Ztime) String() (string, error) {
return this.time.String(), this.err
}
//AddHour 以小时为单位调整时间
/*
##### Example
```go
new(Ztime).Now().SetLocation("Asia/Shanghai").AddHour(-1).Format("2006-01-02T15:04")
```
*/
func (this *Ztime) AddHour(n int) (*Ztime) {
this.time = this.time.Add(time.Duration(n) * time.Hour)
return this
}
//AddMinute 以分钟为单位调整时间
/*
##### Example
```go
new(Ztime).Now().SetLocation("Asia/Shanghai").AddMinute(-1).Format("2006-01-02T15:04")
```
*/
func (this *Ztime) AddMinute(n int) (*Ztime) {
this.time = this.time.Add(time.Duration(n) * time.Minute)
return this
}
//UTC 返回UTC时间
//在当前没有时区文件的场景中可以通过UTC+AddHour计算指定时区的时间
/*
##### Example
```go
new(Ztime).Now().UTC()
```
*/
func (this *Ztime) UTC() (*Ztime) {
this.time = this.time.UTC()
return this
}
// UnixNano 获取Unix纳秒级的时间戳
// lenth返回时间戳长度 length<=13
/*
#### Example
```
t := time.Ztime{}
fmt.Println(t.Now().UnixNano(13))
```
*/
func (this *Ztime) UnixNano(length int) string {
return strconv.FormatInt(this.time.UTC().UnixNano(), 10)[:length]
}