隨筆:Golang 時間Time


先了解下time類型:

type Time struct {

// sec gives the number of seconds elapsed since

// January 1, year 1 00:00:00 UTC.

sec int64

 

// nsec specifies a non-negative nanosecond

// offset within the second named by Seconds.

// It must be in the range [0, 999999999].

nsec int32

 

// loc specifies the Location that should be used to

// determine the minute, hour, month, day, and year

// that correspond to this Time.

// Only the zero Time has a nil Location.

// In that case it is interpreted to mean UTC.

loc *Location

}

對於time.Time類型,我們可以通過使用函數Before,After,Equal來比較兩個time.Time時間:

t1 := time.Now()

t2 := t1.Add(-1 * time.Minute)

fmt.Println(t1.Before(t2))

上面t1是當前時間,t2是當前時間的前一分鍾,輸出結果:false

對於兩個time.Time時間是否相等,也可以直接使用==來判斷:

t1 := time.Now()

t2 := t1.Add(-1 * time.Minute)

fmt.Println(t1 == t2)

 

我們可以通過IsZero來判斷時間Time的零值

t1.IsZero()

 

我們常常會將time.Time格式化為字符串形式:

t := time.Now()

str_t := t.Format("2006-01-02 15:04:05")

至於格式化的格式為什么是這樣的,已經被很多人吐槽了,但是,這是固定寫法,沒什么好說的。

那么如何將字符串格式的時間轉換成time.Time呢?下面兩個函數會比較常用到:

A)

t, _ := time.Parse("2006-01-02 15:04:05", "2017-04-25 09:14:00")

這里我們發現,t:=time.Now()返回的時間是time.Time,上面這行代碼也是time.Time但是打印出來的結果:

2017-04-25 16:15:11.235733 +0800 CST

2016-06-13 09:14:00 +0000 UTC

為什么會不一樣呢?原因是 time.Now() 的時區是 time.Local,而 time.Parse 解析出來的時區卻是 time.UTC(可以通過 Time.Location() 函數知道是哪個時區)。在中國,它們相差 8 小時。

所以,一般的,我們應該總是使用 time.ParseInLocation 來解析時間,並給第三個參數傳遞 time.Local:

t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2017-04-25 16:14:00", time.Local)

之前項目中遇到要獲取某個時間之前的最近整點時間,這個時候有幾種辦法:

t, _ := time.ParseInLocation("2006-01-02 15:04:05", time.Now().Format("2006-01-02 15:00:00"), time.Local)

 

t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2016-06-13 15:34:39", time.Local)

t0:=t.Truncate(1 * time.Hour)

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM