詳解Golang time包中的結(jié)構(gòu)體time.Time
更新時間:2023年07月28日 09:16:03 作者:路多辛
在日常開發(fā)過程中,會頻繁遇到對時間進(jìn)行操作的場景,使用 Golang 中的 time 包可以很方便地實現(xiàn)對時間的相關(guān)操作,本文先講解一下 time 包中的結(jié)構(gòu)體 time.Time,需要的朋友可以參考下
time.Time
time.Time 類型用來表示一個具體的時間點,可以精確到納秒。結(jié)構(gòu)體定義和對應(yīng)的方法如下:
type Time struct {
wall uint64
ext int64
loc *Location
}獲取各種時間點屬性的方法
- 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,獲取月份信息,返回的是一個 Month 類型;
- func (t Time) ISOWeek() (year, week int),返回 ISO 8601 格式的年份和第幾周(1-53)。
- func (t Time) Weekday() Weekday,返回的一個Weekday類型。
- func (t Time) Day() int,獲取月內(nèi)第幾數(shù)(1~31)。
- func (t Time) Clock() (hour, min, sec int),獲取時間(時、分、秒)信息。
- func (t Time) Hour() int,獲取小時信息(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,獲取秒時間戳。
- func (t Time) UnixMilli() int64,獲取毫秒時間戳。
- func (t Time) UnixMicro() int64,獲取微秒時間戳。
- func (t Time) UnixNano() int64,獲取納秒時間戳。
- func (t Time) String() string,返回 "2006-01-02 15:04:05.999999999 -0700 MST" 類型的時間格式。
- func (t Time) Location() *Location,獲取時區(qū)信息。
看個簡單的示例:
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())
}時間處理方法(比較、判斷、解析)
- func (t Time) Format(layout string) string,將時間格式化為指定的格式。
- func (t Time) Add(d Duration) Time,加上指定的時間。
- func (t Time) AddDate(years int, months int, days int) Time,返回將給定的年、月和日數(shù)加到 t 上后所對應(yīng)的時間點。
- func (t Time) Sub(u Time) Duration,返回兩個時間點之間的時間差。
- func (t Time) Truncate(d Duration) Time,截斷指定的時間。
- func (t Time) Round(d Duration) Time,將時間四舍五入到指定的時間。
- func (t Time) Equal(u Time) bool,判斷兩個時間點是否相等。
- func (t Time) After(u Time) bool,判斷 t 時間點是否在 u 時間點后面。
- func (t Time) Before(u Time) bool,判斷 t 時間點是否在 u 時間點前面。
其他方法就不一一說明了,可以參考官方文檔詳細(xì)查看。
到此這篇關(guān)于詳解Golang time包中的結(jié)構(gòu)體time.Time的文章就介紹到這了,更多相關(guān)Golang結(jié)構(gòu)體time.Time內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang內(nèi)存對齊的規(guī)則及實現(xiàn)
本文介紹了Golang內(nèi)存對齊的規(guī)則及實現(xiàn),通過合理的內(nèi)存對齊,可以提高程序的執(zhí)行效率和性能,通過對本文的閱讀,讀者可以更好地理解Golang內(nèi)存對齊的原理和技巧,并應(yīng)用于實際編程中2023-08-08
Go底層之string和[]byte相互轉(zhuǎn)換原理分析
這篇文章主要介紹了Go底層之string和[]byte相互轉(zhuǎn)換原理,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-06-06

