Skip to content

time

go
now := time.Now()
// 现在时间如:
// 2026-03-11 20:56:59.869086 +0800 CST m=+0.000135376
go
then := time.Date( 2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
// 2009-11-17 20:34:58.651387237 +0000 UTC

指定时区

go
loc, _ := time.LoadLocation("Asia/Shanghai")

t := time.Now().In(loc)

时间戳

go
now := time.Now()
secs := now.Unix() // 1773234321
nanos := now.UnixNano() // 1773234321648918000


fmt.Println(time.Unix(secs, 0)) // 2026-03-11 21:07:06 +0800 CST
fmt.Println(time.Unix(0, nanos)) // 2026-03-11 21:07:06.330615 +0800 CST

UTC + RFC3339

go
t := time.Now().UTC().Format(time.RFC3339)

fmt.Println(t) // 2026-03-11T13:12:45Z
go
t1, e := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00")

some api

go
then.Year() // 2009
then.Month() // November
then.Day()  // 17
then.Hour() // 20
then.Minute() // 34
then.Second() // 58
then.Nanosecond() // 651387237
then.Location() // UTC

then.Weekday() // Tuesday

比较 API

go
then.Before(now) // true
then.After(now) // false
then.Equal(now) // false
go
diff := now.Sub(then) // 142984h28m20.705618763s

diff.Hours() // 142984.47241822744
diff.Minutes() // 8.579068345093645e+06
diff.Seconds() // 5.1474410070561874e+08
diff.Nanoseconds() // 514744100705618763

then.Add(diff) // 2026-03-11 13:03:19.357006 +0000 UTC
then.Add(-diff)  // 1993-07-27 04:06:37.945768474 +0000 UTC