新聞中心
時間和日期是我們開發(fā)中經(jīng)常會用到的,Go語言中的 time 包提供了時間顯示和測量等所用的函數(shù),本節(jié)我們就來介紹一下 time 包的基本用法。

兩當(dāng)網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站建設(shè)等網(wǎng)站項目制作,到程序開發(fā),運營維護(hù)。成都創(chuàng)新互聯(lián)于2013年創(chuàng)立到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)。
time 包簡介
時間一般包含時間值和時區(qū),可以從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 的秒數(shù);
- ext:表示納秒;
- loc:代表時區(qū),主要處理偏移量,不同的時區(qū),對應(yīng)的時間不一樣。
如何正確表示時間呢?
公認(rèn)最準(zhǔn)確的計算應(yīng)該是使用“原子震蕩周期”所計算的物理時鐘了(Atomic Clock, 也被稱為原子鐘),這也被定義為標(biāo)準(zhǔn)時間(International Atomic Time)。
而我們常??匆姷?UTC(Universal Time Coordinated,世界協(xié)調(diào)時間)就是利用這種 Atomic Clock 為基準(zhǔn)所定義出來的正確時間。UTC 標(biāo)準(zhǔn)時間是以 GMT(Greenwich Mean Time,格林尼治時間)這個時區(qū)為主,所以本地時間與 UTC 時間的時差就是本地時間與 GMT 時間的時差。
UTC + 時區(qū)差 = 本地時間
國內(nèi)一般使用的是北京時間,與 UTC 的時間關(guān)系如下:
UTC + 8 個小時 = 北京時間
在Go語言的 time 包里面有兩個時區(qū)變量,如下:
- time.UTC:UTC 時間
- time.Local:本地時間
同時,Go語言還提供了 LoadLocation 方法和 FixedZone 方法來獲取時區(qū)變量,如下:
FixedZone(name string, offset int) *Location
其中,name 為時區(qū)名稱,offset 是與 UTC 之前的時差。
LoadLocation(name string) (*Location, error)
其中,name 為時區(qū)的名字。
時間的獲取
1) 獲取當(dāng)前時間
我們可以通過 time.Now() 函數(shù)來獲取當(dāng)前的時間對象,然后通過事件對象來獲取當(dāng)前的時間信息。示例代碼如下:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now() //獲取當(dāng)前時間
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)
}運行結(jié)果如下:
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)至當(dāng)前時間的總毫秒數(shù),它也被稱為 Unix 時間戳(UnixTimestamp)。
基于時間對象獲取時間戳的示例代碼如下:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now() //獲取當(dāng)前時間
timestamp1 := now.Unix() //時間戳
timestamp2 := now.UnixNano() //納秒時間戳
fmt.Printf("現(xiàn)在的時間戳:%v\n", timestamp1)
fmt.Printf("現(xiàn)在的納秒時間戳:%v\n", timestamp2)
}運行結(jié)果如下:
現(xiàn)在的時間戳:1576127858
現(xiàn)在的納秒時間戳:1576127858829900100
使用 time.Unix() 函數(shù)可以將時間戳轉(zhuǎn)為時間格式,示例代碼如下:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now() //獲取當(dāng)前時間
timestamp := now.Unix() //時間戳
timeObj := time.Unix(timestamp, 0) //將時間戳轉(zhuǎn)為時間格式
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)
}運行結(jié)果如下:
2019-12-12 13:24:09 +0800 CST
2019-12-12 13:24:09
3) 獲取當(dāng)前是星期幾
time 包中的 Weekday 函數(shù)能夠返回某個時間點所對應(yīng)是一周中的周幾,示例代碼如下:
package main
import (
"fmt"
"time"
)
func main() {
//時間戳
t := time.Now()
fmt.Println(t.Weekday().String())
}運行結(jié)果如下:
Thursday
時間操作函數(shù)
1) Add
我們在日常的開發(fā)過程中可能會遇到要求某個時間 + 時間間隔之類的需求,Go語言中的 Add 方法如下:
func (t Time) Add(d Duration) Time
Add 函數(shù)可以返回時間點 t + 時間間隔 d 的值。
【示例】求一個小時之后的時間:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
later := now.Add(time.Hour) // 當(dāng)前時間加1小時后的時間
fmt.Println(later)
}運行結(jié)果如下:
2019-12-12 16:00:29.9866943 +0800 CST m=+3600.007978201
2) Sub
求兩個時間之間的差值:
func (t Time) Sub(u Time) Duration
返回一個時間段 t - u 的值。如果結(jié)果超出了 Duration 可以表示的最大值或最小值,將返回最大值或最小值,要獲取時間點 t - d(d 為 Duration),可以使用 t.Add(-d)。
3) Equal
判斷兩個時間是否相同:
func (t Time) Equal(u Time) bool
Equal 函數(shù)會考慮時區(qū)的影響,因此不同時區(qū)標(biāo)準(zhǔn)的時間也可以正確比較,Equal 方法和用 t==u 不同,Equal 方法還會比較地點和時區(qū)信息。
4) Before
判斷一個時間點是否在另一個時間點之前:
func (t Time) Before(u Time) bool
如果 t 代表的時間點在 u 之前,則返回真,否則返回假。
5) After
判斷一個時間點是否在另一個時間點之后:
func (t Time) After(u Time) bool
如果 t 代表的時間點在 u 之后,則返回真,否則返回假。
定時器
使用 time.Tick(時間間隔) 可以設(shè)置定時器,定時器的本質(zhì)上是一個通道(channel),示例代碼如下:
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.Tick(time.Second) //定義一個1秒間隔的定時器
for i := range ticker {
fmt.Println(i) //每秒都會執(zhí)行的任務(wù)
}
}運行結(jié)果如下:
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 方法進(jìn)行格式化,需要注意的是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"))
}運行結(jié)果如下:
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 函數(shù)可以解析一個格式化的時間字符串并返回它代表的時間。
func Parse(layout, value string) (Time, error)
與 Parse 函數(shù)類似的還有 ParseInLocation 函數(shù)。
func ParseInLocation(layout, value string, loc *Location) (Time, error)
ParseInLocation 與 Parse 函數(shù)類似,但有兩個重要的不同之處:
- 第一,當(dāng)缺少時區(qū)信息時,Parse 將時間解釋為 UTC 時間,而 ParseInLocation 將返回值的 Location 設(shè)置為 loc;
- 第二,當(dāng)時間字符串提供了時區(qū)偏移量信息時,Parse 會嘗試去匹配本地時區(qū),而 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)
}運行結(jié)果如下:
2019-12-12 15:22:12 +0000 UTC
2019-12-12 15:22:12 +0800 CST
文章名稱:創(chuàng)新互聯(lián)GO教程:Go語言time包:時間和日期
網(wǎng)頁路徑:http://www.dlmjj.cn/article/coocshj.html


咨詢
建站咨詢
