1. time包
2. time.Time类型,用来表示时间 3. 获取当前时间, now := time.Now() 4. time.Now().Day(),time.Now().Minute(),time.Now().Month(),time.Now().Year() 5. 格式化,fmt.Printf(“%02d/%02d%02d %02d:%02d:%02d”, now.Year()…)
6. 获取当前时间戳,time.Now().Unix()。
7. 时间戳转Time类型。 8. 定时器的简单使用
9. time.Duration⽤来表示纳秒
10 一些常量
const ( Nanosecond Duration = 1 Microsecond = 1000 * Nanosecond Millisecond = 1000 * Microsecond Second = 1000 * Millisecond Minute = 60 * Second Hour = 60 * Minute )
代码
package mainimport ( "fmt" "time")func timeTest() { now := time.Now() fmt.Println(now) year := now.Year() month := now.Month() day := now.Day() hour := now.Hour() minute := now.Minute() second := now.Second() fmt.Printf("%02d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second) // 时间戳 fmt.Println("当前时间戳", now.Unix())}// 将时间戳转换为时间func timestampToTime(timestamp int64) { fmt.Printf("转换的时间为:%v\n", time.Unix(timestamp, 0))}// 讲时间转换为时间戳func timeToStamp(str_time string) { t, _ := time.Parse("2006-01-02 15:04:05", str_time) fmt.Println("当前时间字符串转换为时间戳是", t.Unix()) fmt.Println("当前时间戳是", time.Now().Unix())}func task() { fmt.Println("do task")}// 定时器func timeTick() { tick := time.Tick(1 * time.Second) for i := range tick { fmt.Println(i) task() }}// 常量func testTimeConst() { fmt.Printf("纳秒%d\n", time.Nanosecond) fmt.Printf("微妙%d\n", time.Microsecond) fmt.Printf("毫秒%d\n", time.Millisecond) fmt.Printf("秒%d\n", time.Second) fmt.Printf("分钟%d\n", time.Minute)}func main() { // timeTest() // stamp := time.Now().Unix() // timestampToTime(stamp) // str_time := time.Now().Format("2006-01-02 15:04:05") // 格式化时间固定写成2006-01-02 15:04:05 // fmt.Println(str_time, "str_time") // timeToStamp(str_time) // timeTick() testTimeConst()}