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)
}