1. 获取当前时间:年、月、日、时、分、秒
now := time.Now() //获取当前时间对象
year := now.Year()
month := now.Month()
day := now.Day()
hour := now.Hour()
minute := now.Minute()
second := now.Second()
fmt.Println(year, month, day, hour, minute, second) // 2023 March 14 1 6 19
2.时间操作
两个重点类型:
1.时间类型:type Time struct { wall uint64 ext int64 loc *Location }
2.持续时间类型 单位为1纳秒:type Duration int64
now := time.Now() //获取当前时间对象
// func (t Time) ADD( d Duration) Time
later := now.Add(time.Hour) // 一小时之后
// func (d Duration) Sub(t Time) Duration
sub := now.Sub(later) // 当前时间和一小时之后时间差
// func (t Time)Equal(t Time) bool
res1 := now.Equal(later)
// func (t Time)Before(t Time) bool
res2 := now.Before(later)
// func (t Time)After(t Time) bool
res3 := now.After(later)
fmt.Println(later, sub, res1, res2, res3) // 2023-03-14 02:39:06.915636 +0800 CST m=+3600.000270710 -1h0m0s false true false
3. 时间格式化
go中的格式化为:2006-01-02 15:04:05.000 PM Mon Jan
- 年:2006
- 月:01
- 日:02
- 时:15
- 分:04
- 秒:05
- 保留小数:000
- 12小时制:PM
- 几月星期几:Mon Jan
now := time.Now()
t1 := now.Format("2006-01-02 15:04:05")
fmt.Println(t1)
t2 := now.Format("2006-01-02 15:04:05 ")
fmt.Println(t2)
t3 := now.Format("2006-01-02 15:04:05 PM Mon Jan")
fmt.Println(t3)
t4 := now.Format("2006-01-02 15:04:05.000 PM Mon Jan")
fmt.Println(t4)
t5 := now.Format("2006-01-02 15:04:05.999 PM Mon Jan") //999省略末尾出现的0
fmt.Println(t5)
2023-03-14 02:00:28
2023-03-14 02:00:28
2023-03-14 02:00:28 AM Tue Mar
2023-03-14 02:00:28.410 AM Tue Mar
2023-03-14 02:00:28.41 AM Tue Mar
4.定时器
func time.Tick(d time.Duration) <-chan time.Time
tick:= time.Tick(time.Second*4)
for i :=range tick{
fmt.Println(i) //每4秒执行一次
}