go语言中涉及时间的操作基本都会用到time包,本文整理了go中对时间常做的一些操作。
1.获取时间
now := time.Now() //获取当前时间
year_now := now.Year() //获取当前年份
month_now := now.Month() //获取当前月份
day_now := now.Day() //获取当前日期
hour_now := now.Hour() //获取当前小时
minute_now := now.Minute() //获取当前分钟
second_now := now.Second() //获取当前秒
fmt.Printf("current time:%s\n%d年%d月%d日%d时%d分%d秒\n", now, year_now, month_now, day_now, hour_now, minute_now, second_now)
fmt.Println("**********************************")
//获取时间戳
timesunix := time.Now().Unix() //获取当前时间戳
fmt.Println("timeunix:", timesunix)
fmt.Println("**********************************")
//获取星期几 weekday函数
weekday := now.Weekday() //获取weekday
fmt.Println("weekday:", weekday)
输出:
current time:2022-07-15 15:24:14.752518 +0800 CST m=+0.000107213
2022年7月15日15时24分14秒
**********************************
timeunix: 1657869854
**********************************
weekday: Friday
2.时间计算
时间调整
// 调整时间 add函数
t1 := now.Add(time.Hour * -24) //前一天
t2 := now.Add(time.Hour * 2) //后两小时
fmt.Println("last day:", t1)
fmt.Println("next 2 hour:", t2)
输出:
last day: 2022-07-14 16:06:39.253978 +0800 CST m=-86399.999890405
next 2 hour: 2022-07-15 18:06:39.253978 +0800 CST m=+7200.000109595
时间差值计算
//求时间差 sub函数
t3 := now.Add(time.Hour + time.Minute*30) //一小时30分钟以后
t4 := now.Add(time.Second * -30) //30秒之前
t5 := time.Date(2022, 6, 20, 10, 30, 23, 0, time.Local) //指定时间
fmt.Println("t5:", t5)
fmt.Println("t3-now:", t3.Sub(now))
fmt.Println("now-t3:", now.Sub(t3))
fmt.Println("t4-now:", t4.Sub(now))
fmt.Println("t5-now:", t5.Sub(now))
输出:
t5: 2022-06-20 10:30:23 +0800 CST
t3-now: 1h30m0s
now-t3: -1h30m0s
t4-now: -30s
t5-now: -605h36m16.253978s
判断时间前后
//判断时间前后 before after eauql
t6 := now.Add(time.Second * 30) //30s后
t7 := time.Date(2021, 1, 1, 1, 1, 1, 0, time.Local) //指定时间
fmt.Println("t6 before now:", t6.Before(now))
fmt.Println("now before t6:", now.Before(t6))
fmt.Println("t7 after now:", t7.After(now))
fmt.Println("now after t7:", now.After(t7))
输出:
t6 before now: false
now before t6: true
t7 after now: false
now after t7: true
3.time与string类型转换
//time类型转string
timeString := now.Format("2006 01 02 15:04:05")
fmt.Println("timeString:", timeString)
fmt.Println("timeString type:", reflect.TypeOf(timeString))
//string类型转time
timestamp, _ := time.ParseInLocation("2006-01-02 15:04:05", timeString, time.Local)
fmt.Println("timestamp:", timestamp)
fmt.Println("timestamp type:", reflect.TypeOf(timestamp))
输出:
timeString: 2022 07 15 16:06:39
timeString type: string
timestamp: 0001-01-01 00:00:00 +0000 UTC
timestamp type: time.Time