在日常開發(fā)過程中,會(huì)頻繁遇到對(duì)時(shí)間進(jìn)行操作的場(chǎng)景,使用 Golang 中的 time 包可以很方便地實(shí)現(xiàn)對(duì)時(shí)間的相關(guān)操作。接下來的幾篇文章會(huì)詳細(xì)講解 time 包,本文先講解一下 time 包中的結(jié)構(gòu)體 time.Time。
time.Time
time.Time 類型用來表示一個(gè)具體的時(shí)間點(diǎn),可以精確到納秒。結(jié)構(gòu)體定義和對(duì)應(yīng)的方法如下:
type Time struct {
wall uint64
ext int64
loc *Location
}
獲取各種時(shí)間點(diǎn)屬性的方法
- func (t Time) Date() (year int, month Month, day int),獲取日期(年、月、日)信息。
- func (t Time) Year() int,獲取年份信息。
- func (t Time) YearDay() int,獲取一年中第幾天(1~365)。
- func (t Time) Month() Month,獲取月份信息,返回的是一個(gè) Month 類型;
- func (t Time) ISOWeek() (year, week int),返回?ISO 8601 格式的年份和第幾周(1-53)。
- func (t Time) Weekday() Weekday,返回的一個(gè)Weekday類型。
- func (t Time) Day() int,獲取月內(nèi)第幾數(shù)(1~31)。
- func (t Time) Clock() (hour, min, sec int),獲取時(shí)間(時(shí)、分、秒)信息。
- func (t Time) Hour() int,獲取小時(shí)信息(0~23)。
- func (t Time) Minute() int,獲取分鐘信息(0~59)。
- func (t Time) Second() int,獲取秒信息(0~59)。
- func (t Time) Nanosecond() int,獲取納秒信息(0~999999999)。
- func (t Time) Unix() int64,獲取秒時(shí)間戳。
- func (t Time) UnixMilli() int64,獲取毫秒時(shí)間戳。
- func (t Time) UnixMicro() int64,獲取微秒時(shí)間戳。
- func (t Time) UnixNano() int64,獲取納秒時(shí)間戳。
- func (t Time) String() string,返回?"2006-01-02 15:04:05.999999999 -0700 MST" 類型的時(shí)間格式。
- func (t Time) Location() *Location,獲取時(shí)區(qū)信息。
看個(gè)簡(jiǎn)單的示例:文章來源:http://www.zghlxwxcb.cn/news/detail-609682.html
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
fmt.Println(t.Date())
fmt.Println(t.Year())
fmt.Println(t.YearDay())
fmt.Println(t.Month())
fmt.Println(t.ISOWeek())
fmt.Println(t.Weekday())
fmt.Println(t.Day())
fmt.Println(t.Clock())
fmt.Println(t.Hour())
fmt.Println(t.Minute())
fmt.Println(t.Second())
fmt.Println(t.Nanosecond())
fmt.Println(t.Unix())
fmt.Println(t.UnixMilli())
fmt.Println(t.UnixMicro())
fmt.Println(t.UnixNano())
fmt.Println(t.String())
fmt.Println(t.Location())
}
時(shí)間處理方法(比較、判斷、解析)
- func (t Time) Format(layout string) string,將時(shí)間格式化為指定的格式。
- func (t Time) Add(d Duration) Time,加上指定的時(shí)間。
- func (t Time) AddDate(years int, months int, days int) Time,返回將給定的年、月和日數(shù)加到 t 上后所對(duì)應(yīng)的時(shí)間點(diǎn)。
- func (t Time) Sub(u Time) Duration,返回兩個(gè)時(shí)間點(diǎn)之間的時(shí)間差。
- func (t Time) Truncate(d Duration) Time,截?cái)嘀付ǖ臅r(shí)間。
- func (t Time) Round(d Duration) Time,將時(shí)間四舍五入到指定的時(shí)間。
- func (t Time) Equal(u Time) bool,判斷兩個(gè)時(shí)間點(diǎn)是否相等。
- func (t Time) After(u Time) bool,判斷 t 時(shí)間點(diǎn)是否在 u 時(shí)間點(diǎn)后面。
- func (t Time) Before(u Time) bool,判斷 t 時(shí)間點(diǎn)是否在 u 時(shí)間點(diǎn)前面。
其他方法就不一一說明了,可以參考官方文檔詳細(xì)查看。文章來源地址http://www.zghlxwxcb.cn/news/detail-609682.html
到了這里,關(guān)于Golang 中的 time 包詳解(一):time.Time的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!