Go中的time

909 阅读3分钟

这是我参与8月更文挑战的第18天,活动详情查看:8月更文挑战

年月日时分秒

 // 获取当前时间
 now := time.Now()
 fmt.Printf("%#v \n", now)
 ​
 // 获取年
 fmt.Println(now.Year())
 ​
 // 获取月
 fmt.Println(now.Month())
 ​
 // 获取日
 fmt.Println(now.Day())
 ​
 // 获取小时
 fmt.Println(now.Hour())
 ​
 // 获取分钟
 fmt.Println(now.Minute())
 ​
 // 获取秒
 fmt.Println(now.Second())
 ​
 // 获取纳秒
 fmt.Println(now.Nanosecond())

时间格式化

对应的时间格式字符串 年: 2006 月: 1 日: 2 时: 03 | 15 12小时制使用03, 24小时制使用15 分: 04 秒: 05

 // 将时间格式化成字符串
 timeStr := now.Format("2006年1月2日 03:04:05")
 fmt.Println(timeStr)
 ​
 // 将字符串解析成时间
 timeStr2 := "2021-08-16 11:06:30"
 ​
 // 时间格式化样式
 layout := "2006-01-02 03:04:05"
 ​
 // 指定时区
 loc, err := time.LoadLocation("Asia/Shanghai")
 if err != nil {
    fmt.Println("parse in location failed: ", err)
    return
 }
 // 解析指定时区的时间
 parseTime, err := time.ParseInLocation(layout, timeStr2, loc)
 ​
 // 不指定时区, 返回UTC时间
 //parseTime, err := time.Parse(layout, timeStr2)
 if err != nil {
    fmt.Println("time parse failed: ", err)
 }
 fmt.Println(parseTime)

时间戳

 // 获取秒时间戳
 // 当前时间距离1970年1月1日所过去多少秒
 timeUnix := now.Unix()
 fmt.Println("时间转换为秒时间戳: ", timeUnix)
 ​
 // 获取纳秒时间戳
 // 当前时间距离1970年1月1日所过去多少纳秒
 timeUnixNano := now.UnixNano()
 fmt.Println("时间转换为纳秒时间戳: ", timeUnixNano)
 ​
 // 将时间戳转为时间
 /*
 我们指定一个时间戳, 然后将它转换为对应的时间
 */
 t1 := time.Unix(timeUnix + int64(60 * 60), 0)
 fmt.Println(t1)

时间间隔

Go语言中的时间间隔, 是通过int64定义的一个新类型

type Duration int64

数值大小代表多少纳秒, 我们可以使用定义好的时间间隔常量间接使用时间单位

 Nanosecond  Duration = 1
 Microsecond          = 1000 * Nanosecond
 Millisecond          = 1000 * Microsecond
 Second               = 1000 * Millisecond
 Minute               = 60 * Second
 Hour                 = 60 * Minute
 // 让程序睡眠1s
 time.Sleep(time.Second * 1)
 ​
 // 让程序睡眠500毫秒
 time.Sleep(time.Millisecond * 500)

时间的运算

 // 时间运算
 fmt.Println("当前时间: ", now)
 ​
 // add
 // 1小时后
 fmt.Println("1小时后: ", now.Add(time.Hour * 1))
 ​
 // 1天后
 fmt.Println("1天后: ", now.Add(time.Hour * 24))
 ​
 // 1小时前
 fmt.Println("1小时前: ", now.Add(-time.Hour * 1))
 ​
 // 1天前
 fmt.Println("1天前: ", now.Add(-time.Hour * 24))
 ​
 // sub
 time1 := time.Now()
 time2 := time.Now().Add(-time.Hour * 10)
 subTime := time1.Sub(time2)
 fmt.Println(subTime.Hours())
 fmt.Println(subTime.Minutes())

定时器

 // 可以指定它的时间间隔
 // Tick函数返回的是一个time类型的通道
 timer := time.Tick(time.Second)
 for i := range timer {
    fmt.Println(i)
 }

time中的常量

Month

 /*
 在Go中将1~12月定义为了一个新的类型Month, 实际类型为int, 值为1~12
 */
 type Month int
 ​
 const (
    January Month = 1 + iota
    February
    March
    April
    May
    June
    July
    August
    September
    October
    November
    December
 )

Weekday

 /*
 通过int定义了一个新的类型Weekday, 周日为0, 周一到周六为: 1~6
 */
 type Weekday int
 ​
 const (
    Sunday Weekday = iota
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
 )

总结

在time包中提供了丰富的方法, 我们可以很简单的获取当前时间的年月日时分秒, 获取当前时间的时间戳, 也可以很方便的将时间戳转换为时间. 提供了时间的运算方法. 还可以使用通道实现的定时器来完成一些定时任务!!!