隨筆:Golang 時間Time

先了解下time類型:函數

type Time struct {this

// sec gives the number of seconds elapsed sincespa

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

sec int64ci

 

// nsec specifies a non-negative nanosecond字符串

// offset within the second named by Seconds.it

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

nsec int32class

 

// loc specifies the Location that should be used tosed

// 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)

相關文章
相關標籤/搜索