Skip to content

Instantly share code, notes, and snippets.

@xin053
Last active April 4, 2020 06:54
Show Gist options
  • Select an option

  • Save xin053/528e90a596dd1ae2d4c2b8a1715aa030 to your computer and use it in GitHub Desktop.

Select an option

Save xin053/528e90a596dd1ae2d4c2b8a1715aa030 to your computer and use it in GitHub Desktop.
[go time] go time #go #time
// 获取指定月份的天数
package main
import (
"fmt"
"time"
)
func days(year int, month time.Month) int {
return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()
}
func main() {
fmt.Println(days(2019, 2)) // 28
fmt.Printf("%v", time.Date(2019, 3, 0, 0, 0, 0, 0, time.UTC)) // 2019-02-28 00:00:00 +0000 UTC
}
// 时间格式化
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
}
// 计算程序运行时间
package main
import (
"fmt"
"time"
)
func main() {
startTime := time.Now()
time.Sleep(1 * time.Second)
elapsed := time.Since(startTime)
fmt.Printf("elapsed %v", elapsed) // elapsed 1.0005049s
}

time 包 After 源码

// After waits for the duration to elapse and then sends the current time
// on the returned channel.
// It is equivalent to NewTimer(d).C.
// The underlying Timer is not recovered by the garbage collector
// until the timer fires. If efficiency is a concern, use NewTimer
// instead and call Timer.Stop if the timer is no longer needed.
func After(d Duration) <-chan Time {
    return NewTimer(d).C
}

调用time.After(duration)后,此函数马上返回,返回一个time.Time类型的 Chan,不阻塞,后面你该做什么做什么,不影响,到了duration时间后,自动发送当前时间到管道中,经常与 select 一起使用.

func requestWithTimeout(timeout time.Duration) (int, error) {
	c := make(chan int)
	// May need a long time to get the response.
	go doRequest(c)

	select {
	case data := <-c:
		return data, nil
	case <-time.After(timeout):
		return 0, errors.New("timeout")
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment