Go语言的时间类型(time)

Go语言的时间类型(time)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 源码来自Go 1.19
// 源码包:/usr/local/go/src/time/time.go
type Time struct {
// wall and ext encode the wall time seconds, wall time nanoseconds,
// and optional monotonic clock reading in nanoseconds.
//
// From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
// a 33-bit seconds field, and a 30-bit wall time nanoseconds field.
// The nanoseconds field is in the range [0, 999999999].
// If the hasMonotonic bit is 0, then the 33-bit field must be zero
// and the full signed 64-bit wall seconds since Jan 1 year 1 is stored in ext.
// If the hasMonotonic bit is 1, then the 33-bit field holds a 33-bit
// unsigned wall seconds since Jan 1 year 1885, and ext holds a
// signed 64-bit monotonic clock reading, nanoseconds since process start.
wall uint64
ext int64

// loc specifies the Location that should be used to
// determine the minute, hour, month, day, and year
// that correspond to this Time.
// The nil location means UTC.
// All UTC times are represented with loc==nil, never loc==&utcLoc.
loc *Location
}

wall:表示距离公元 1 年 1 月 1 日 00:00:00UTC 的秒数;
ext:表示纳秒;
loc:代表时区,主要处理偏移量,不同的时区,对应的时间不一样;

公认最准确的计算应该是使用“原子震荡周期”所计算的物理时钟了(Atomic Clock, 也被称为原子钟),这也被定义为标准时间(International Atomic Time)

而我们常常看见的 UTC(Universal Time Coordinated,世界协调时间)就是利用这种 Atomic Clock 为基准所定义出来的正确时间。UTC 标准时间是以 GMT(Greenwich Mean Time,格林尼治时间)这个时区为主,所以本地时间与 UTC 时间的时差就是本地时间与 GMT 时间的时差
UTC + 时区差 = 本地时间

国内一般使用的是北京时间,与 UTC 的时间关系如下:
UTC + 8 个小时 = 北京时间

在Go语言的 time 包里面有两个时区变量,如下:

  • time.UTC:UTC 时间
  • time.Local:本地时间

获取当前时间

我们可以通过time.Now()函数来获取当前的时间对象,然后通过事件对象来获取当前的时间信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now() //获取当前时间
fmt.Printf("current time:%v\n", now)
year := now.Year() //年
month := now.Month() //月
day := now.Day() //日
hour := now.Hour() //小时
minute := now.Minute() //分钟
second := now.Second() //秒
fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

时间操作函数

我们在日常的开发过程中可能会遇到要求某个时间 + 时间间隔之类的需求,Go语言中的 Add 方法实现
func (t Time) Add(d Duration) Time

1
2
3
4
5
6
7
8
9
10
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
later := now.Add(time.Hour) // 当前时间加1小时后的时间
fmt.Println(later)
}

求两个时间之间的差值
func (t Time) Sub(u Time) Duration

判断两个时间是否相同,会考虑时区的影响,因此不同时区标准的时间也可以正确比较
func (t Time) Equal(u Time) bool

如果t代表的时间点在u之前,返回真;否则返回假
func (t Time) Before(u Time) bool

如果t代表的时间点在u之后,返回真;否则返回假
func (t Time) After(u Time) bool

定时器

使用time.Tick(时间间隔)来设置定时器,定时器的本质上是一个通道(channel)

1
2
3
4
5
6
func TestTick() {
ticker := time.Tick(time.Second) //定义一个1秒间隔的定时器
for i := range ticker {
fmt.Println(i)//每秒都会执行的任务
}
}