【笔记】Go语言的日期和时间

前言

Go语言的日期和时间学习笔记

引入依赖

1
import time

创建对象

当前日期和时间

1
var t time.Time = time.Now()

任意日期和时间

1
var t time.Time = time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC)

获取年月日时分秒

1
2
3
4
5
6
t.Year()
int(t.Month())
t.Day()
t.Hour()
t.Minute()
t.Second()

时间常量

1
2
3
4
5
6
time.Hour
time.Minute
time.Second
time.Millisecond
time.Microsecond
time.Nanosecond

增减年月日

1:向后偏移1年
2:向后偏移2个月
3:向后偏移3天

1
t = t.AddDate(1, 2, 3)

-1:向前偏移1年
-2:向前偏移2个月
-3:向前偏移3天

1
t = t.AddDate(-1, -2, -3)

增减时分秒

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
incrementHour, err := time.ParseDuration("1h")
t = t.Add(incrementHour)

incrementMinute, err := time.ParseDuration("1m")
t = t.Add(incrementMinute)

incrementSecond, err := time.ParseDuration("1s")
t = t.Add(incrementSecond)

incrementMillisecond, err := time.ParseDuration("1ms")
t = t.Add(incrementMillisecond)

incrementMicrosecond, err := time.ParseDuration("1us")
t = t.Add(incrementMicrosecond)

incrementNanosecond, err := time.ParseDuration("1ns")
t = t.Add(incrementNanosecond)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
incrementHour, err := time.ParseDuration("-1h")
t = t.Add(incrementHour)

incrementMinute, err := time.ParseDuration("-1m")
t = t.Add(incrementMinute)

incrementSecond, err := time.ParseDuration("-1s")
t = t.Add(incrementSecond)

incrementMillisecond, err := time.ParseDuration("-1ms")
t = t.Add(incrementMillisecond)

incrementMicrosecond, err := time.ParseDuration("-1us")
t = t.Add(incrementMicrosecond)

incrementNanosecond, err := time.ParseDuration("-1ns")
t = t.Add(incrementNanosecond)

偏移量计算

1
2
increment, err := time.ParseDuration("1h")
increment = increment * 2

计算日期和时间差值

1
2
3
4
var t1 time.Time
var t2 time.Time

var t time.Time = t1.Sub(t2)

比较日期和时间

1
2
3
4
5
6
var t1 time.Time
var t2 time.Time

var result1 bool = t1.Before(t2)
var result2 bool = t1.After(t2)
var result3 bool = t1.Equal(t2)

日期和时间与时间戳互转

日期和时间转换为时间戳

  • 秒级时间戳
1
t.Unix()
  • 毫秒级时间戳
1
t.UnixMilli()
  • 微秒级时间戳
1
t.UnixMicro()
  • 纳秒级时间戳
1
t.UnixNano()

时间戳转换为日期和时间对象

1
var t time.Time = time.Unix(<timestamp>, 0)

格式化日期和时间

日期和时间转换为字符串

1
var str string = t.Format("2006-01-02 15:04:05")

字符串转换为日期和时间

1
2
var str string = "2006-01-02 15:04:05"
t, err := time.Parse("2006-01-02 15:04:05", str)

指定时区

定义为当前时区

1
2
var zone = time.FixedZone("Local", 0)
t.In(zone)

定义为东八区

1
2
var zone = time.FixedZone("CST", 8*3600)
t.In(zone)

定义为上海时间

1
2
var zone, _ = time.LoadLocation("Asia/Shanghai")
time.Now().In(zone)

延迟

阻塞延迟

1
time.Sleep(1 * time.Second)

非阻塞延迟

  • 返回一个通道,该通道会在指定时间后发送一个时间戳
1
<-time.After(1 * time.Second)

完成

参考文献

哔哩哔哩——尚硅谷
CSDN——zy_whynot
CSDN——CodyGuo
CSDN——Golang发烧友
亿速云——iii
极客教程