-
Notifications
You must be signed in to change notification settings - Fork 5
/
time_fast.go
99 lines (80 loc) · 2.28 KB
/
time_fast.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
// Copyright 2023 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package fasttime
import (
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
"github.com/TeaOSLab/EdgeNode/internal/goman"
"github.com/iwind/TeaGo/types"
timeutil "github.com/iwind/TeaGo/utils/time"
"time"
)
var sharedFastTime = NewFastTime()
func init() {
if !teaconst.IsMain {
return
}
var ticker = time.NewTicker(200 * time.Millisecond)
goman.New(func() {
for range ticker.C {
sharedFastTime = NewFastTime()
}
})
}
func Now() *FastTime {
return sharedFastTime
}
type FastTime struct {
rawTime time.Time
unixTime int64
unixTimeMilli int64
unixTimeMilliString string
ymd string
round5Hi string
hour int
}
func NewFastTime() *FastTime {
var rawTime = time.Now()
return &FastTime{
rawTime: rawTime,
unixTime: rawTime.Unix(),
unixTimeMilli: rawTime.UnixMilli(),
unixTimeMilliString: types.String(rawTime.UnixMilli()),
ymd: timeutil.Format("Ymd", rawTime),
round5Hi: timeutil.FormatTime("Hi", rawTime.Unix()/300*300),
hour: rawTime.Hour(),
}
}
// Unix 最快获取时间戳的方式,通常用在不需要特别精确时间戳的场景
func (this *FastTime) Unix() int64 {
return this.unixTime
}
// UnixFloor 取整
func (this *FastTime) UnixFloor(seconds int) int64 {
return this.unixTime / int64(seconds) * int64(seconds)
}
// UnixCell 取整并加1
func (this *FastTime) UnixCell(seconds int) int64 {
return this.unixTime/int64(seconds)*int64(seconds) + int64(seconds)
}
// UnixNextMinute 获取下一分钟开始的时间戳
func (this *FastTime) UnixNextMinute() int64 {
return this.UnixCell(60)
}
// UnixMilli 获取时间戳,精确到毫秒
func (this *FastTime) UnixMilli() int64 {
return this.unixTimeMilli
}
func (this *FastTime) UnixMilliString() (int64, string) {
return this.unixTimeMilli, this.unixTimeMilliString
}
func (this *FastTime) Ymd() string {
return this.ymd
}
func (this *FastTime) Round5Hi() string {
return this.round5Hi
}
func (this *FastTime) Format(layout string) string {
return timeutil.Format(layout, this.rawTime)
}
func (this *FastTime) Hour() int {
return this.hour
}