• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

[go]time包

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

go by example: time

time常用api

// time包
now := time.Now() 
fmt.Printf("current time:%v\n", now) //2019-12-04 21:37:22.138938 +0800 CST m=+0.000109570
//格式化时间
year := now.Year()
month := now.Month()
day := now.Day()
hour := now.Hour()
minute := now.Minute()
send := now.Second()
fmt.Printf("%02d-%02d-%02d %02d:%02d:%02d\n", year, month, day ,hour, minute, send)
//格式化时间
now := time.Now()
timeStr := now.Format("2006/01/02 15:04:05")  //go诞⽣于2006-01-02 15:04:05
fmt.Printf("time:%s\n", timeStr)
//格式化时间
now := time.Now()
timeStr := fmt.Sprintf("%02d/%02d/%02d %02d:%02d:%02d\n", now.Year(), now.Month(), now.Day() ,now.Hour(), now.Minute(), now.Second())
fmt.Printf("time:%s\n", timeStr)
//时间戳
timestamp := time.now().Unix() //unix时间戳,int64

timeObj := time.Unix(timestamp, 0)
year := timeObj.Year()
month := timeObj.Month()
day := timeObj.Day()
hour := timeObj.Hour()
minute := timeObj.Minute()
send := timeObj.Second()

fmt.Printf("current timestamp:%d\n", timestamp)
fmt.Printf("%02d-%02d-%02d %02d:%02d:%02d\n", year, month, day ,hour, minute, send)
//时间常量
fmt.Printf("nano second:%d\n", time.Nanosecond)
fmt.Printf("micro second:%d\n", time.Microsecond)
fmt.Printf("mili second:%d\n", time.Millisecond)
fmt.Printf("second:%d\n", time.Second)
//给出时间字符串 计算时间差
const TIME_LAYOUT = "2006/01/02 15:04:05" //时间格式模版,跟时间字符串格式一致
str := "2018/09/10 00:00:00"
t, _ := time.Parse(TIME_LAYOUT, str) //将时间转换为
fmt.Println(t)
fmt.Println(t.Sub(time.Now()).Milliseconds()) //-38929603501
//给出时间戳转换为时间

var ts int64= 1575467403
u := time.Unix(ts, 0)
fmt.Println(u)
//睡1s

time.Sleep(time.Second)
<-time.NewTimer(time.Second).C
<-time.After(time.Second)
// 定时+回调(setTimeout)

time.AfterFunc(time.Second, func() {
	println("after 1s cb")
})
time.Sleep(time.Second*3)
// 周期定时(setInterval)

ticker := time.Tick(1*time.Second)
for i := range ticker {
	fmt.Printf("%v\n", i)
	processTask()
}
// 周期定时(setInterval)

for  {
	<-time.NewTicker(time.Second).C
	println(1)
}
timer.Stop()            //清除定时器
timer.Reset(time.Second)//重置定时器
//比较时间早晚(返回bool)

time.Now().Before(time.Now()) //true, 在这个时间之前吗
time.Now().After(time.Now())
time.Now().Equal(time.Now())
//计算耗时

t := time.Now()
latency := time.Since(t)
//获取随机数
rand.Seed(time.Now().UnixNano()) //确保执行多次生成的随机数不同
fmt.Println(rand.Intn(200))
fmt.Println(rand.Intn(200))

//随机睡眠多久
rand.Intn(200) //随机获取200内整数
time.Duration(rand.Intn(200)) //强制转换为Duration即类型, type Duration int64

time.Sleep(time.Duration(10 * time.Millisecond)
time.Sleep(time.Duration(rand.Intn(200)) * time.Millisecond)

timer源码

// Timer源码
type Timer struct {
	C <-chan Time
	r runtimeTimer
}


func NewTimer(d Duration) *Timer {
	c := make(chan Time, 1)
	t := &Timer{
		C: c,
		r: runtimeTimer{
			when: when(d),
			f:    sendTime,
			arg:  c,
		},
	}
	startTimer(&t.r)
	return t
}
  • tickTimer
func main() {
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()
	done := make(chan bool)
	go func() {
		time.Sleep(10 * time.Second)
		done <- true
	}()
	for {
		select {
		case <-done:
			fmt.Println("Done!")
			return
		case t := <-ticker.C:
			fmt.Println("Current time: ", t)
		}
	}
}

//源码
type Ticker struct {
	C <-chan Time // The channel on which the ticks are delivered.
	r runtimeTimer
}

func NewTicker(d Duration) *Ticker {
	if d <= 0 {
		panic(errors.New("non-positive interval for NewTicker"))
	}

	c := make(chan Time, 1)
	t := &Ticker{
		C: c,
		r: runtimeTimer{
			when:   when(d),
			period: int64(d),
			f:      sendTime,
			arg:    c,
		},
	}
	startTimer(&t.r)
	return t
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
两分钟让你明白Go中如何继承发布时间:2022-07-10
下一篇:
[Go]imap收信非并发发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap