time應該是開發中比較常用的庫了,常見方法說明:
package main
import (
"time"
"fmt"
)
func main() {
a := time.Now().Unix()
fmt.Println("時間戳---", a)
// 2006-01-02 15:04:05 記住這一刻
b := time.Now().Format("2006-01-02 15:04:05")
fmt.Println("格式化時間", b)
/**
func (t Time) Add(d Duration) Time
Duration如下
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
*/
c := time.Now().Add(time.Minute * 3)
fmt.Println("3分鐘後時間", c.Format("2006-01-02 15:04:05"))
/**
func (t Time) AddDate(years int, months int, days int) Time
*/
d := time.Now().AddDate(-1, 1,10)
fmt.Println("時間", d.Format("2006-01-02 15:04:05"))
// 返回年月日三個值
fmt.Println(time.Now().Date())
// 返回時分秒三個值
fmt.Println(time.Now().Clock())
fmt.Println(time.Now().Year(), time.Now().Month(), time.Now().Day())
fmt.Println(time.Now().Weekday(), time.Now().Hour())
fmt.Println(time.Now().YearDay())
fmt.Println(time.Since(d))
// tring返回採用如下格式字串的格式化時間。
// "2006-01-02 15:04:05.999999999 -0700 MST"
fmt.Println(time.Now().String())
time.AfterFunc(2*time.Second, func() {
fmt.Println("hello 2s")
})
loc, _ := time.LoadLocation("Asia/Shanghai")
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
const shortForm = "2006-Jan-02"
t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
fmt.Println(t)
/**
func ParseInLocation(layout, value string, loc *Location) (Time, error)
*/
t, _ = time.ParseInLocation(shortForm, "2022-Jul-09", loc)
fmt.Println(t)
/**
func Parse(layout, value string) (Time, error)
解析一個格式化的時間字串並返回它代表的時間
ParseInLocation類似Parse但有兩個重要的不同之處。
第一,當缺少時區資訊時,Parse將時間解釋為UTC時間,而ParseInLocation將返回值的Location設定為loc;
第二,當時間字串提供了時區偏移量資訊時,Parse會嘗試去匹配本地時區,而ParseInLocation會去匹配loc
*/
t, _ = time.Parse(longForm, "Feb 3, 2023 at 7:54pm (PST)")
fmt.Println(t)
t, _ = time.Parse(shortForm, "2020-Feb-03")
fmt.Println(t)
ch := make(chan int)
timeout := time.After(time.Second * 2)
timer := time.NewTimer(time.Second * 4)
var i int
go func() {
for {
// i++
select {
case <- ch:
fmt.Println("channel close")
return
case <- timer.C:
fmt.Println("4s的NewTimer定時任務")
case <- timeout:
fmt.Println("4s定時輸出")
case <- time.After(time.Second * 6):
fmt.Println("6s到了")
// default:
// //Sleep 1秒,引數就是上面的Duration
// time.Sleep(time.Second * 1)
// fmt.Println("go 1s")
}
}
}()
time.Sleep(time.Second * 15)
fmt.Println("close----")
close(ch)
time.Sleep(time.Second * 2)
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
收藏前不妨點個贊試試!!!
分享開發知識,歡迎交流。qq交流群:965666112,公眾號:愛好歷史的程式設計師。
點選直達個人部落格