1.获取当前时间:
nowTime := time.Now()
fmt.Println(nowTime)//2018-09-29 14:05:44.298275318 +0800 CST m=+0.000667643
2.获取当前时间的年月日时分秒:
fmt.Println("年",nowTime.Year())
fmt.Println("月",nowTime.Month())
fmt.Println("日",nowTime.Day())
fmt.Println("小时",nowTime.Hour())
fmt.Println("分钟",nowTime.Minute())
fmt.Println("秒钟",nowTime.Second())
3.按照我们指定的方式生产字符串:
//第一种方式
fmt.Printf("当前的时间是: %d-%d-%d %d:%d:%d\n", nowTime.Year(),
nowTime.Month(), nowTime.Day(), nowTime.Hour(), nowTime.Minute(), nowTime.Second())
str := fmt.Sprintf("当前的时间是: %d-%d-%d %d:%d:%d\n", nowTime.Year(),
nowTime.Month(), nowTime.Day(), nowTime.Hour(), nowTime.Minute(), nowTime.Second())
fmt.Println(str)
//第二种方式
// 2006/01/02 15:04:05 这个字符串是Go语言规定的, 各个数字都是固定的
// 字符串中的各个数字可以只有组合, 这样就能按照需求返回格式化好的时间
// 其它语言 : yyyy-MM-dd HH:mm:ss
//strFormat := nowTime.Format("2006-01-02 15:04:05")
//strFormat := nowTime.Format("2006-01-02")
//strFormat := nowTime.Format("15:04:05")
//strFormat := nowTime.Format("2006")
//strFormat := nowTime.Format("2006/01/02 15:04:05")
//strFormat := nowTime.Format("2006/01/02")
strFormat := nowTime.Format("15|04|05")
fmt.Println(strFormat)
4.时间常量的使用:
for{
// 每隔1秒打印一次
//time.Sleep(time.Second)
// 每隔0.1秒打印一次
//time.Sleep(time.Second * 0.1)
time.Sleep(time.Millisecond * 100)
fmt.Println("我被打印了")
}
5.时间戳的使用:
// go语言中的时间戳是从1970年1月1日开始计算的
// Unix: 返回当前时间距离1970年1月1日有多少秒
// UnixNano: 返回当前时间距离1970年1月1日有多少纳秒
fmt.Println(time.Now().Unix()) // 秒
fmt.Println(time.Now().UnixNano()) // 纳秒