您現在的位置是:首頁 > 音樂首頁音樂
golang2021函式與包(56)Go語言time包:時間和日期
時區數是什麼意思
時間和日期是我們開發中經常會用到的,Go語言中的 time 包提供了時間顯示和測量等所用的函式,本節我們就來介紹一下 time 包的基本用法。
time 包簡介
時間一般包含時間值和時區,可以從Go語言中 time 包的原始碼中看出:
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:本地時間
同時,Go語言還提供了 LoadLocation 方法和 FixedZone 方法來獲取時區變數,如下:
FixedZone(name string, offset int) *Location
其中,name 為時區名稱,offset 是與 UTC 之前的時差。
LoadLocation(name string) (*Location, error)
其中,name 為時區的名字。
時間的獲取
1) 獲取當前時間
我們可以透過 time。Now() 函式來獲取當前的時間物件,然後透過事件物件來獲取當前的時間資訊。示例程式碼如下:
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)
}
執行結果如下:
current time:2019-12-12 12:33:19。4712277 +0800 CST m=+0。006980401
2019-12-12 12:33:19
2) 獲取時間戳
時間戳是自 1970 年 1 月 1 日(08:00:00GMT)至當前時間的總毫秒數,它也被稱為 Unix 時間戳(UnixTimestamp)。
基於時間物件獲取時間戳的示例程式碼如下:
package main
import (
“fmt”
“time”
)
func main() {
now := time。Now() //獲取當前時間
timestamp1 := now。Unix() //時間戳
timestamp2 := now。UnixNano() //納秒時間戳
fmt。Printf(“現在的時間戳:%v\n”, timestamp1)
fmt。Printf(“現在的納秒時間戳:%v\n”, timestamp2)
}
執行結果如下:
現在的時間戳:1576127858
現在的納秒時間戳:1576127858829900100
使用 time。Unix() 函式可以將時間戳轉為時間格式,示例程式碼如下:
package main
import (
“fmt”
“time”
)
func main() {
now := time。Now() //獲取當前時間
timestamp := now。Unix() //時間戳
timeObj := time。Unix(timestamp, 0) //將時間戳轉為時間格式
fmt。Println(timeObj)
year := timeObj。Year() //年
month := timeObj。Month() //月
day := timeObj。Day() //日
hour := timeObj。Hour() //小時
minute := timeObj。Minute() //分鐘
second := timeObj。Second() //秒
fmt。Printf(“%d-%02d-%02d %02d:%02d:%02d\n”, year, month, day, hour, minute, second)
}
執行結果如下:
2019-12-12 13:24:09 +0800 CST
2019-12-12 13:24:09
3) 獲取當前是星期幾
time 包中的 Weekday 函式能夠返回某個時間點所對應是一週中的周幾,示例程式碼如下:
package main
import (
“fmt”
“time”
)
func main() {
//時間戳
t := time。Now()
fmt。Println(t。Weekday()。String())
}
執行結果如下:
Thursday
時間操作函式
1) Add
我們在日常的開發過程中可能會遇到要求某個時間 + 時間間隔之類的需求,Go語言中的 Add 方法如下:
func (t Time) Add(d Duration) Time
Add 函式可以返回時間點 t + 時間間隔 d 的值。
【示例】求一個小時之後的時間:
package main
import (
“fmt”
“time”
)
func main() {
now := time。Now()
later := now。Add(time。Hour) // 當前時間加1小時後的時間
fmt。Println(later)
}
執行結果如下:
2019-12-12 16:00:29。9866943 +0800 CST m=+3600。007978201
2) Sub
求兩個時間之間的差值:
func (t Time) Sub(u Time) Duration
返回一個時間段 t - u 的值。如果結果超出了 Duration 可以表示的最大值或最小值,將返回最大值或最小值,要獲取時間點 t - d(d 為 Duration),可以使用 t。Add(-d)。
3) Equal
判斷兩個時間是否相同:
func (t Time) Equal(u Time) bool
Equal 函式會考慮時區的影響,因此不同時區標準的時間也可以正確比較,Equal 方法和用 t==u 不同,Equal 方法還會比較地點和時區資訊。
4) Before
判斷一個時間點是否在另一個時間點之前:
func (t Time) Before(u Time) bool
如果 t 代表的時間點在 u 之前,則返回真,否則返回假。
5) After
判斷一個時間點是否在另一個時間點之後:
func (t Time) After(u Time) bool
如果 t 代表的時間點在 u 之後,則返回真,否則返回假。
定時器
使用 time。Tick(時間間隔) 可以設定定時器,定時器的本質上是一個通道(channel),示例程式碼如下:
package main
import (
“fmt”
“time”
)
func main() {
ticker := time。Tick(time。Second) //定義一個1秒間隔的定時器
for i := range ticker {
fmt。Println(i) //每秒都會執行的任務
}
}
執行結果如下:
2019-12-12 15:14:26。4158067 +0800 CST m=+16。007460701
2019-12-12 15:14:27。4159467 +0800 CST m=+17。007600701
2019-12-12 15:14:28。4144689 +0800 CST m=+18。006122901
2019-12-12 15:14:29。4159581 +0800 CST m=+19。007612101
2019-12-12 15:14:30。4144337 +0800 CST m=+20。006087701
。。。
時間格式化
時間型別有一個自帶的 Format 方法進行格式化,需要注意的是Go語言中格式化時間模板不是常見的Y-m-d H:M:S 而是使用Go語言的誕生時間 2006 年 1 月 2 號 15 點 04 分 05 秒。
提示:如果想將時間格式化為 12 小時格式,需指定 PM。
package main
import (
“fmt”
“time”
)
func main() {
now := time。Now()
// 格式化的模板為Go的出生時間2006年1月2號15點04分 Mon Jan
// 24小時制
fmt。Println(now。Format(“2006-01-02 15:04:05。000 Mon Jan”))
// 12小時制
fmt。Println(now。Format(“2006-01-02 03:04:05。000 PM Mon Jan”))
fmt。Println(now。Format(“2006/01/02 15:04”))
fmt。Println(now。Format(“15:04 2006/01/02”))
fmt。Println(now。Format(“2006/01/02”))
}
執行結果如下:
2019-12-12 15:20:52。037 Thu Dec
2019-12-12 03:20:52。037 PM Thu Dec
2019/12/12 15:20
15:20 2019/12/12
2019/12/12
解析字串格式的時間
Parse 函式可以解析一個格式化的時間字串並返回它代表的時間。
func Parse(layout, value string) (Time, error)
與 Parse 函式類似的還有 ParseInLocation 函式。
func ParseInLocation(layout, value string, loc *Location) (Time, error)
ParseInLocation 與 Parse 函式類似,但有兩個重要的不同之處:
第一,當缺少時區資訊時,Parse 將時間解釋為 UTC 時間,而 ParseInLocation 將返回值的 Location 設定為 loc;
第二,當時間字串提供了時區偏移量資訊時,Parse 會嘗試去匹配本地時區,而 ParseInLocation 會去匹配 loc。
示例程式碼如下:
package main
import (
“fmt”
“time”
)
func main() {
var layout string = “2006-01-02 15:04:05”
var timeStr string = “2019-12-12 15:22:12”
timeObj1, _ := time。Parse(layout, timeStr)
fmt。Println(timeObj1)
timeObj2, _ := time。ParseInLocation(layout, timeStr, time。Local)
fmt。Println(timeObj2)
}
執行結果如下:
2019-12-12 15:22:12 +0000 UTC
2019-12-12 15:22:12 +0800 CST