time := time.Now()
fmt.Printf("time type = %T,time = %v\n",time,time)
now := time.Now()
fmt.Printf("time type = %T,time = %v\n",now,now)
fmt.Printf("年 = %v\n",now.Year())
fmt.Printf("月 = %v\n",now.Month()) //返回的是 英文的 月份,可以使用int转换为对应的数字月份
fmt.Printf("月 = %v\n",int(now.Month()))
fmt.Printf("日 = %v\n",now.Day())
fmt.Printf("时 = %v\n",now.Hour()) // 范围[0,23]
fmt.Printf("分 = %v\n",now.Minute()) // [0,59]
fmt.Printf("秒 = %v\n",now.Second()) // [0,59]
方式一: 使用 Printf 或 Sprintf
now := time.Now()
fmt.Printf("%02d-%02d-%02d %02d:%02d:%02d",now.Year(),now.Month(),now.Day(),now.Hour(),now.Minute(),now.Second())
now := time.Now()
timestr := fmt.Sprintf("%02d-%02d-%02d %02d:%02d:%02d",now.Year(),now.Month(),now.Day(),now.Hour(),now.Minute(),now.Second())
fmt.Println("当前时间: ",timestr)
now := time.Now()
timestr := fmt.Sprintf(now.Format("2006-01-02 15:04:05"))
fmt.Println("当前时间: ",timestr)
注意:
2006-01-02 15:04:05 各个数字是固定的,必须这样写,但是可以自由组合成各种格式。例如 2006/01/02, 2006年01月02日等
const (
Nanosecond Duration = 1 // 1纳秒
Microsecond = 1000 * Nanosecond //微妙
Millisecond = 1000 * Microsecond //毫秒
Second = 1000 * Millisecond //秒
Minute = 60 * Second //分钟
Hour = 60 * Minute //小时
)
作用: 获取指定时间单位的时间,例如: 100毫秒 100 * time.Millisecond
fmt.Println("休眠3秒")
time.Sleep(3 * time.Second)
fmt.Println("123")
// 每隔1秒输出一个数字
for i := 0; i < 10; i++ {
fmt.Println(i)
time.Sleep(time.Second)
}
now := time.Now()
fmt.Printf("unix时间戳 = %v unixnano时间戳 = %v\n",now.Unix(),now.UnixNano())