Go笔记-时间

当前时间

可使用 time.Now() 获取,或者使用 t.Day()t.Minute() 等等来获取时间的一部分;你甚至能够自定义时间格式化字符串,例如: fmt.Printf("%02d.%02d.%4d\n”, t.Day(), t.Month(), t.Year()) 将会输出 21.07.2011。ide

time.Nanosecond() 并非从70年开始的纳秒,UnixNano() 才是。函数

函数执行时间

start := time.Now()
doSomeThing()
end := time.Now()
delta := end.Sub(start)
fmt.Printf("doSomeThing took this amount of time: %s\n", delta) // 纳秒

格式化时间

func Now() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

输出示例:ui

2015-03-15 09:48:34
y, m, d := time.Now().Date()
	h, mi, s := time.Now().Clock()
	fmt.Printf("如今是:%d年%d月%d日 %d时%d分%d秒 \n", y, m, d, h, mi, s)

输出:this

如今是:2015年3月15日 9时55分12秒

timezone

now := time.Now()
	s := now.Format("20060102150405")
	t, err := time.Parse("20060102150405", s)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(now, t)

上面输出:2016-01-25 19:15:31.21773073 +0800 CST 2016-01-25 19:15:31 +0000 UTCcode

Parse是按照UTC来解析的。orm

若是想按照本地时区来解析的话使用:time.ParseInLocation("20060102150405", s, time.Local)资源

定时器

time.NewTimer(time.Second * 2)

NewTimer建立一个Timer,它会在最少过去时间段d后到期,向其自身的C字段发送当时的时间。字符串

// Timers represent a single event in the future. You
	// tell the timer how long you want to wait, and it
	// provides a channel that will be notified at that
	// time. This timer will wait 2 seconds.
	timer1 := time.NewTimer(time.Second * 2)

	// The `<-timer1.C` blocks on the timer's channel `C`
	// until it sends a value indicating that the timer
	// expired.
	<-timer1.C
	fmt.Println("Timer 1 expired")

	// If you just wanted to wait, you could have used
	// `time.Sleep`. One reason a timer may be useful is
	// that you can cancel the timer before it expires.
	// Here's an example of that.
	timer2 := time.NewTimer(time.Second)
	go func() {
		<-timer2.C
		fmt.Println("Timer 2 expired")
	}()
	stop2 := timer2.Stop()
	if stop2 {
		fmt.Println("Timer 2 stopped")
	}

运行结果string

Timer 1 expired
Timer 2 stopped

Ticker

time.NewTicker(time.Millisecond * 500)

NewTicker返回一个新的Ticker,该Ticker包含一个通道字段,并会每隔时间段d就向该通道发送当时的时间。它会调整时间间隔或者丢弃tick信息以适应反应慢的接收者。若是d<=0会panic。关闭该Ticker能够释放相关资源。it

// Tickers use a similar mechanism to timers: a
	// channel that is sent values. Here we'll use the
	// `range` builtin on the channel to iterate over
	// the values as they arrive every 500ms.
	ticker := time.NewTicker(time.Millisecond * 500)
	go func() {
		for t := range ticker.C {
			fmt.Println("Tick at", t)
		}
	}()

	// Tickers can be stopped like timers. Once a ticker
	// is stopped it won't receive any more values on its
	// channel. We'll stop ours after 1500ms.
	time.Sleep(time.Millisecond * 1500)
	ticker.Stop()
	fmt.Println("Ticker stopped")

运行结果

Tick at 2015-04-22 09:58:52.048046619 +0800 CST
Tick at 2015-04-22 09:58:52.548034081 +0800 CST
Tick at 2015-04-22 09:58:53.048019367 +0800 CST
Ticker stopped
相关文章
相关标签/搜索