Go + time包
原创
©著作权归作者所有:来自51CTO博客作者xiaoxiaoyu8510的原创作品,请联系作者获取转载授权,否则将追究法律责任
1.timestamp转string,和北京时间一致
//9位秒时间?要再测试下
func GetTimeStrFromTimeStamp(iTimeStamp int64) string{
strTime := time.Unix(iTimeStamp, 0).Format("2006-01-02 15:04:05.000")
return strTime
}
转UTC时间,比北京时间慢8个小时
dayStamp := 1584432887
//time.Unix(sec int64, nsec int64)
//nsec要小于1e9,即小于1000000000
utcTime := time.Unix(int64(dayStamp), int64(123000000)).UTC().Format("2006-01-02T15:04:05.000Z")
fmt.Printf("%s\n", utcTime) //打印的是UTC时间,时间格式: 2020-03-17T08:14:47.123Z
2. string 转timestamp
func GetSecondByTimeStr(strTime string)(error, int64){
timeTemplate := "2006-01-02 15:04:05" //常规类型
tTime, err := time.ParseInLocation(timeTemplate, strTime, time.Local)
if nil != err {
return err, 0
}
timeStamp := tTime.Unix()
return nil, timeStamp
}
3.获取给定日期的0点时间戳
func GetZeroPointTimeStamp(iSrcStamp int64) (int64, error) {
tm := time.Unix(iSrcStamp/1000, 0)
strTime := tm.Format("2006-01-02") + " 00:00:00"
timeTemplate := "2006-01-02 15:04:05" //常规类型
tTime, err := time.ParseInLocation(timeTemplate, strTime, time.Local)
if nil != err {
return 0, err
}
timeStamp := tTime.Unix() * 1000
return timeStamp, err
}
3.定时器
a.ticker 如果ticker函数被阻塞的话,后面的ticker还是会等本ticker完成以后,继续执行
ticker := time.NewTicker(time.Second * 5)
ticker.Stop() //Stop会停止Ticker,停止后,Ticker不会再被发送,但是Stop不会关闭通道,防止读取通道发生错误,所以如下用法会导致携程被阻塞,不会退出,资源泄漏
ticker := time.NewTicker(time.Second * 5)
go func(){
log.Debug("go runtine is running,and wait for ticker")
for range ticker.C{
log.Debug("ticker exe")
}
log.Debug("go runtine exit")
}()
正确的用法:
func UserTicker() chan bool {
ticker := time.NewTicker(5 * time.Second)
stopChan := make(chan bool)
go func(ticker *time.Ticker) {
defer ticker.Stop()
for {
select {
case <-ticker.C:
fmt.Println("Ticker2....")
case stop := <-stopChan:
if stop {
fmt.Println("Ticker2 Stop")
return
}
}
}
}(ticker)
return stopChan
}
func main() {
ch := UserTicker()
time.Sleep(20 * time.Second)
ch <- true
close(ch)
}
b. NewTimer
timer := time.NewTimer(5 * time.Second)
log.Debug("create timer")
for{
<-timer.C
log.Debug("get timer")
timer.Reset(10 * time.Second) //timer默认只会触发一次,Reset后
}
4.统计函数执行的时间
func trace(msg string) func() {
start := time.Now()
fmt.Printf("enter %s\n", msg)
return func() {
fmt.Printf("exit %s (%s)\n", msg, time.Since(start))
}
}
//调用: note:不要忘记defer语句后的圆括号,否则本该在进入时执行的操作会在退出时执行,
//而本该在退出时执行的,永远不会执行
defer trace("sum")()