您好,欢迎访问一九零五行业门户网

学会 Go 中的时间处理

作为程序员,我们经常需要对时间进行处理。在 go 中,标准库 time 提供了对应的能力。
本文将介绍 time 库中一些重要的函数和方法,希望能帮助到那些一遇到 go 时间处理问题就需要百度的童鞋。
应对时区问题在编程中,我们经常会遭遇八小时时间差问题。这是由时区差异引起的,为了能更好地解决它们,我们需要理解几个时间定义标准。
gmt(greenwich mean time),格林威治平时。gmt 根据地球的自转和公转来计算时间,它规定太阳每天经过位于英国伦敦郊区的皇家格林威治天文台的时间为中午12点。gmt 是前世界标准时。
utc(coordinated universal time),协调世界时。utc 比 gmt 更精准,它根据原子钟来计算时间。在不需要精确到秒的情况下,可以认为 utc=gmt。utc 是现世界标准时。
从格林威治本初子午线起,往东为正,往西为负,全球共划分为 24 个标准时区,相邻时区相差一个小时。
package mainimport ( "fmt" "time")func main() { fmt.println(time.now())}
中国大陆使用的是东八时区的标准时,即北京时间 cst,china standard time。
$ go run main.go 2022-07-17 16:37:31.186043 +0800 cst m=+0.000066647
这是默认时区下的结果,time.now()的打印中会标注+0800 cst。
假设我们是在美国洛杉矶时区下,那得到的结果是什么呢?
$ tz="america/los_angeles" go run main.go2022-07-17 01:39:12.391505 -0700 pdt m=+0.000069514
可以看到,此时的结果是-0700 pdt 时间,即 pdt(pacific daylight time)太平洋夏季时间。由于时区差异,两次执行的时间结果相差了 15 小时。
注意,在使用 docker 容器时,系统默认的时区就是 utc 时间(0 时区),和我们实际需要的北京时间相差八个小时,这是导致八小时时间差问题的经典场景。
时区问题的应对策略,可以详细查看 src/time/zoneinfo_unix.go 中 initlocal() 函数的加载逻辑。例如,可以通过指定环境变量 tz,修改/etc/localtime文件等方式来解决。
因为时区问题非常重要,所以放在了文章第一部分讲述。下面开始介绍 time 库的使用。
时间瞬间 time.timetime 库,最核心的对象是 time.time 结构体。它的定义如下,用以表示某个瞬间的时间。
type time struct { // wall and ext encode the wall time seconds, wall time nanoseconds, // and optional monotonic clock reading in nanoseconds. wall uint64 ext int64 loc *location}
计算机在时间处理上,主要涉及到两种时钟。
墙上时钟(wall time),又称为钟表时间,用于表示具体的日期与时间。
单调时钟(monotonic clocks),总是保证时间是向前的,不会出现墙上时钟的回拨问题,因此它很适合用于测量持续时间段。
wall 和 ext 字段就是用于记录墙上时钟和单调时钟,精度为纳秒。字段的对应位数上关联着用于确定时间的具体年、月、日、小时、分钟、秒等信息。
loc 字段记录时区位置,当 loc 为 nil 时,默认为 utc 时间。
因为 time.time 用于表示具有纳秒精度的时间瞬间,在程序中通常应该将它作为值存储和传递,而不是指针。
即在时间变量或者结构体字段中,我们应该使用 time.time,而非 *time.time。
获取 time.time我们可以通过 now 函数获取当前本地时间
func now() time {}
也可以通过 date 函数,根据年、月、日等时间和时区参数获取指定时间
func date(year int, month month, day, hour, min, sec, nsec int, loc *location) time {}
转换时间戳计算机世界中,将 utc 时间 1970 年1月1日 0 时 0 分 0 秒作为 unix 时间 0。所谓的时间瞬间转换为 unix 时间戳,即计算的是从 unix 时间 0 到指定瞬间所经过的秒数、微秒数等。
func (t time) unix() int64 {} // 从 unix 时间 0 经过的秒数func (t time) unixmicro() int64 {} // 从 unix 时间 0 经过的微秒数func (t time) unixmilli() int64 {} // 从 unix 时间 0 经过的毫秒数func (t time) unixnano() int64 {} // 从 unix 时间 0 经过的纳秒数
获取基本字段 t := time.now() fmt.println(t.date()) // 2022 july 17 fmt.println(t.year()) // 2022 fmt.println(t.month()) // july fmt.println(t.isoweek()) // 2022 28 fmt.println(t.clock()) // 22 21 56 fmt.println(t.day()) // 17 fmt.println(t.weekday()) // sunday fmt.println(t.hour()) // 22 fmt.println(t.minute()) // 21 fmt.println(t.second()) // 56 fmt.println(t.nanosecond())// 494313000 fmt.println(t.yearday()) // 198
持续时间 time.duration持续时间 time.duration 用于表示两个时间瞬间 time.time 之间所经过的时间。它通过 int64 表示纳秒计数,能表示的极限大约为 290 年。
// a duration represents the elapsed time between two instants// as an int64 nanosecond count. the representation limits the// largest representable duration to approximately 290 years.type duration int64
在 go 中,持续时间只是一个以纳秒为单位的数字而已。如果持续时间等于 1000000000,则它代表的含义是 1 秒或 1000 毫秒或 1000000 微秒或 1000000000 纳秒。
例如,相隔 1 小时的两个时间瞬间 time.time 值,它们之间的持续时间 time.duration 值为
1*60*60*1000*1000*1000
go 的 time 包中定义了这些持续时间常量值
const ( nanosecond duration = 1 microsecond = 1000 * nanosecond millisecond = 1000 * microsecond second = 1000 * millisecond minute = 60 * second hour = 60 * minute)
同时,time.duration 提供了能获取各时间粒度数值的方法
func (d duration) nanoseconds() int64 {} // 纳秒func (d duration) microseconds() int64 {} // 微秒func (d duration) milliseconds() int64 {} // 毫秒func (d duration) seconds() float64 {} // 秒func (d duration) minutes() float64 {} // 分钟func (d duration) hours() float64 {} // 小时
时间计算在学习了时间瞬间和持续时间之后,我们来看如何做时间计算。
func (t time) add(d duration) time {}
add 函数用于增加/减少( d 的正值表示增加、负值表示减少) time.time 的持续时间。我们可以对某瞬时时间,增加或减少指定纳秒级以上的时间。func (t time) sub(u time) duration {}
sub 函数可以得出两个时间瞬间之间的持续时间。func (t time) adddate(years int, months int, days int) time {}
adddate 函数基于年、月和日的维度增加/减少 time.time 的值。当然,基于当前时间瞬间 time.now() 的计算是最普遍的需求。因此,time 包还提供了以下便捷的时间计算函数。
func since(t time) duration {}
since 函数是 time.now().sub(t) 的快捷方法。
func until(t time) duration {}
until 函数是 t.sub(time.now()) 的快捷方法。
使用示例 t := time.now() fmt.println(t) // 2022-07-17 22:41:06.001567 +0800 cst m=+0.000057466 //时间增加 1小时 fmt.println(t.add(time.hour * 1)) // 2022-07-17 23:41:06.001567 +0800 cst m=+3600.000057466 //时间增加 15 分钟 fmt.println(t.add(time.minute * 15))// 2022-07-17 22:56:06.001567 +0800 cst m=+900.000057466 //时间增加 10 秒钟 fmt.println(t.add(time.second * 10))// 2022-07-17 22:41:16.001567 +0800 cst m=+10.000057466 //时间减少 1 小时 fmt.println(t.add(-time.hour * 1)) // 2022-07-17 21:41:06.001567 +0800 cst m=-3599.999942534 //时间减少 15 分钟 fmt.println(t.add(-time.minute * 15))// 2022-07-17 22:26:06.001567 +0800 cst m=-899.999942534 //时间减少 10 秒钟 fmt.println(t.add(-time.second * 10))// 2022-07-17 22:40:56.001567 +0800 cst m=-9.999942534 time.sleep(time.second * 5) t2 := time.now() // 计算 t 到 t2 的持续时间 fmt.println(t2.sub(t)) // 5.004318874s // 1 年之后的时间 t3 := t2.adddate(1, 0, 0) // 计算从 t 到当前的持续时间 fmt.println(time.since(t)) // 5.004442316s // 计算现在到明年的持续时间 fmt.println(time.until(t3)) // 8759h59m59.999864s
格式化时间在其他语言中,一般会使用通用的时间模板来格式化时间。例如 python,它使用 %y 代表年、%m 代表月、%d 代表日等。
但是,go 不一样,它使用固定的时间(需要注意,使用其他的时间是不可以的)作为布局模板,而这个固定时间是 go 语言的诞生时间。
mon jan 2 15:04:05 mst 2006
格式化时间涉及到两个转换函数
func parse(layout, value string) (time, error) {}
parse 函数用于将时间字符串根据它所能对应的布局转换为 time.time 对象。func (t time) format(layout string) string {}
formate 函数用于将 time.time 对象根据给定的布局转换为时间字符串。示例const ( layoutiso = "2006-01-02" layoutus = "january 2, 2006")date := "2012-08-09"t, _ := time.parse(layoutiso, date)fmt.println(t) // 2012-08-09 00:00:00 +0000 utcfmt.println(t.format(layoutus)) // august 9, 2012
在 time 库中,go 提供了一些预定义的布局模板常量,这些可以直接拿来使用。
const ( layout = "01/02 03:04:05pm '06 -0700" // the reference time, in numerical order. ansic = "mon jan _2 15:04:05 2006" unixdate = "mon jan _2 15:04:05 mst 2006" rubydate = "mon jan 02 15:04:05 -0700 2006" rfc822 = "02 jan 06 15:04 mst" rfc822z = "02 jan 06 15:04 -0700" // rfc822 with numeric zone rfc850 = "monday, 02-jan-06 15:04:05 mst" rfc1123 = "mon, 02 jan 2006 15:04:05 mst" rfc1123z = "mon, 02 jan 2006 15:04:05 -0700" // rfc1123 with numeric zone rfc3339 = "2006-01-02t15:04:05z07:00" rfc3339nano = "2006-01-02t15:04:05.999999999z07:00" kitchen = "3:04pm" // handy time stamps. stamp = "jan _2 15:04:05" stampmilli = "jan _2 15:04:05.000" stampmicro = "jan _2 15:04:05.000000" stampnano = "jan _2 15:04:05.000000000")
下面是我们可选的布局参数对照表
年 06/2006月 01/1/jan/january日 02/2/_2星期 mon/monday小时 03/3/15分 04/4秒 05/5毫秒 .000/.999微秒 .000000/.999999纳秒 .000000000/.999999999am/pm pm/pm时区 mst时区小时数差-0700/-07/-07:00/z0700/z07:00
时区转换在文章开头,我们介绍了时区问题。如果在代码中,需要获取同一个 time.time 在不同时区下的结果,我们可以使用它的 in 方法。
func (t time) in(loc *location) time {}
它的使用非常简单,直接看示例代码
now := time.now()fmt.println(now) // 2022-07-18 21:19:59.9636 +0800 cst m=+0.000069242loc, _ := time.loadlocation("utc")fmt.println(now.in(loc)) // 2022-07-18 13:19:59.9636 +0000 utcloc, _ = time.loadlocation("europe/berlin")fmt.println(now.in(loc)) // 2022-07-18 15:19:59.9636 +0200 cestloc, _ = time.loadlocation("america/new_york")fmt.println(now.in(loc)) // 2022-07-18 09:19:59.9636 -0400 edtloc, _ = time.loadlocation("asia/dubai")fmt.println(now.in(loc)) // 2022-07-18 17:19:59.9636 +0400 +04
总结整体而言,time 库提供的时间处理函数和方法,基本满足我们的使用需求。
以上就是学会 go 中的时间处理的详细内容。
其它类似信息

推荐信息