github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/fasttime/time_fast.go (about) 1 // Copyright 2023 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn . 2 3 package fasttime 4 5 import ( 6 teaconst "github.com/TeaOSLab/EdgeNode/internal/const" 7 "github.com/TeaOSLab/EdgeNode/internal/goman" 8 "github.com/iwind/TeaGo/types" 9 timeutil "github.com/iwind/TeaGo/utils/time" 10 "time" 11 ) 12 13 var sharedFastTime = NewFastTime() 14 15 func init() { 16 if !teaconst.IsMain { 17 return 18 } 19 20 var ticker = time.NewTicker(200 * time.Millisecond) 21 goman.New(func() { 22 for range ticker.C { 23 sharedFastTime = NewFastTime() 24 } 25 }) 26 } 27 28 func Now() *FastTime { 29 return sharedFastTime 30 } 31 32 type FastTime struct { 33 rawTime time.Time 34 unixTime int64 35 unixTimeMilli int64 36 unixTimeMilliString string 37 ymd string 38 round5Hi string 39 hour int 40 } 41 42 func NewFastTime() *FastTime { 43 var rawTime = time.Now() 44 45 return &FastTime{ 46 rawTime: rawTime, 47 unixTime: rawTime.Unix(), 48 unixTimeMilli: rawTime.UnixMilli(), 49 unixTimeMilliString: types.String(rawTime.UnixMilli()), 50 ymd: timeutil.Format("Ymd", rawTime), 51 round5Hi: timeutil.FormatTime("Hi", rawTime.Unix()/300*300), 52 hour: rawTime.Hour(), 53 } 54 } 55 56 // Unix 最快获取时间戳的方式,通常用在不需要特别精确时间戳的场景 57 func (this *FastTime) Unix() int64 { 58 return this.unixTime 59 } 60 61 // UnixFloor 取整 62 func (this *FastTime) UnixFloor(seconds int) int64 { 63 return this.unixTime / int64(seconds) * int64(seconds) 64 } 65 66 // UnixCell 取整并加1 67 func (this *FastTime) UnixCell(seconds int) int64 { 68 return this.unixTime/int64(seconds)*int64(seconds) + int64(seconds) 69 } 70 71 // UnixNextMinute 获取下一分钟开始的时间戳 72 func (this *FastTime) UnixNextMinute() int64 { 73 return this.UnixCell(60) 74 } 75 76 // UnixMilli 获取时间戳,精确到毫秒 77 func (this *FastTime) UnixMilli() int64 { 78 return this.unixTimeMilli 79 } 80 81 func (this *FastTime) UnixMilliString() (int64, string) { 82 return this.unixTimeMilli, this.unixTimeMilliString 83 } 84 85 func (this *FastTime) Ymd() string { 86 return this.ymd 87 } 88 89 func (this *FastTime) Round5Hi() string { 90 return this.round5Hi 91 } 92 93 func (this *FastTime) Format(layout string) string { 94 return timeutil.Format(layout, this.rawTime) 95 } 96 97 func (this *FastTime) Hour() int { 98 return this.hour 99 }