[go]time包

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
}