該包提供了對於時間的顯示、轉換以及控制。
精度一直實現到納秒函數
type Duration int64 顯示時間間隔
type Location struct 設置顯示的時區
type Month int 顯示月份
type Weekday int 顯示星期
type ParseError struct 解析錯誤spa
type Time struct 時間轉換code
type Ticker struct 時鐘
type Timer structorm
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("begin")
resTime := <-time.After(3 * time.Second)
fmt.Printf(
"after 3 second\nNow the time is %s\n",
resTime.Format("2006-01-02 15:04:05"))
}
複製代碼
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("begin")
time.Sleep(3000 * time.Millisecond)
fmt.Printf("after 3 second\n")
}
複製代碼
package main
import (
"fmt"
"log"
"time"
)
func main() {
locate, _ := time.LoadLocation("Asia/Shanghai")
c := time.Tick(2 * time.Second)
i := 0
for now := range c {
i++
fmt.Printf(
"%s, 定時器第%d次運行\n",
now.In(locate).Format("2006-01-02 15:04:05"), i)
}
}
複製代碼
時間間隔(type Duration int64)以納秒爲最小單元協程
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
複製代碼
由於Duration也爲int類型,因此上面的代碼能夠經過 2 * time.Second 的方式得到對應的數字。
這個數字能夠做爲Duration傳入函數中。string
package main
import (
"fmt"
"log"
"time"
)
func main() {
locate, _ := time.LoadLocation("Asia/Shanghai")
fmt.Printf(
"當前時區:%s, 當前時間:%s\n", locate.String(),
time.Now().In(locate).Format("2006-01-02 15:04:05"))
locate2 := time.FixedZone("UTC-8", 0)
fmt.Printf("當前時區:%s(東八區),當前時間:%s\n",
locate2.String(),
time.Now().In(locate2).Format("2006-01-02 15:04:05"))
}
複製代碼
package main
import (
"fmt"
"log"
"time"
)
func main() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
t := <-ticker.C
fmt.Println(t.In(time.FixedZone("UTC-8", 0)).Format("2006-01-02 15:04:05"))
}
}
複製代碼
package main
import (
"fmt"
"log"
"time"
)
func main() {
// 時間戳轉日期時間
curDateTime := time.Now().In(time.FixedZone("UTC-8", 0)).Format("2006-01-02 15:04:05")
fmt.Println(curDateTime)
// 日期轉時間戳
parseTime, _ := time.Parse("2006-01-02 15:04:05", curDateTime)
fmt.Println(parseTime.Unix())
}
複製代碼