Go语言提供了对时间和时间段的广泛支持;以下是一些示例。
package main
import (
"fmt"
"time"
)
func main() {
p := fmt.Println
// 我们将从获取当前时间开始。
now := time.Now()
p(now)
// 您可以通过提供年、月、日等信息来构建一个时间结构体。时间总是与一个位置(即时区)相关联。
then := time.Date(
2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
p(then)
// 您可以按预期提取时间值的各个组成部分。
p(then.Year())
p(then.Month())
p(then.Day())
p(then.Hour())
p(then.Minute())
p(then.Second())
p(then.Nanosecond())
p(then.Location())
// 周一至周日的星期几信息同样可用。
p(then.Weekday())
// 这些方法用于比较两个时间,分别测试第一个时间是否在第二个时间之前、之后或与之同时发生。
p(then.Before(now))
p(then.After(now))
p(then.Equal(now))
// Sub方法返回一个表示两个时间之间间隔的Duration。
diff := now.Sub(then)
p(diff)
// 我们可以用不同的单位计算时间段的长度。
p(diff.Hours())
p(diff.Minutes())
p(diff.Seconds())
p(diff.Nanoseconds())
// 您可以使用Add来将时间向前推进一个给定的时间段,或者使用-来向后移动一个时间段。
p(then.Add(diff))
p(then.Add(-diff))
}运行结果:
➜ go run time/time.go
2025-01-17 09:38:07.541084 +0800 CST m=+0.000067001
2009-11-17 20:34:58.651387237 +0000 UTC
2009
November
17
20
34
58
651387237
UTC
Tuesday
true
false
false
132941h3m8.889696763s
132941.0524693602
7.976463148161612e+06
4.785877888896968e+08
478587788889696763
2025-01-17 01:38:07.541084 +0000 UTC
1994-09-18 15:31:49.761690474 +0000 UTC原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。