提升編程技能:學(xué)習(xí)如何在Go語言中正確格式化時間
先來看一個簡單的例子:
package main import ( "fmt" "time" ) func main() { fmt.Println(time.Now().Format("2006")) }
我們會覺得這會輸出什么呢?輸出的是 2022
,也就是當前年份。
另一個例子:
package main import ( "fmt" "time" ) func main() { fmt.Println(time.Now().Format("2006-01-02 15:04:05")) }
輸出:2022-08-04 09:43:56
如果之前寫其他語言的,看到這個結(jié)果估計和我一樣覺得百思不得其解,為什么不是 Y-m-d H:i:s
這種格式呢?而且那個參數(shù)看起來就是一個時間戳。
那個參數(shù)真的是時間戳嗎?
答案我們可以點開 Format
的源碼看看就知道了:
func (t Time) Format(layout string) string { // ... 省略,下面這個調(diào)用才是關(guān)鍵 b = t.AppendFormat(b, layout) // ... 省略 }
我們看到 Format
里面具體處理邏輯在 AppendFormat
函數(shù)里面,再點開 AppendFormat
看看:
switch std & stdMask { case stdYear: y := year if y < 0 { y = -y } b = appendInt(b, y%100, 2) case stdLongYear: b = appendInt(b, year, 4) case stdMonth: b = append(b, month.String()[:3]...) case stdLongMonth: m := month.String() b = append(b, m...) // ... 省略其他 case }
我們可以看到里面的 stdYear
、stdLongYear
之類的常量實際上就是我們傳入到 Format
的參數(shù)里面的數(shù)字。
const ( _ = iota stdLongMonth = iota + stdNeedDate // "January" stdMonth // "Jan" stdNumMonth // "1" stdZeroMonth // "01" stdLongWeekDay // "Monday" stdWeekDay // "Mon" stdDay // "2" stdUnderDay // "_2" stdZeroDay // "02" stdUnderYearDay // "__2" stdZeroYearDay // "002" stdHour = iota + stdNeedClock // "15" stdHour12 // "3" stdZeroHour12 // "03" stdMinute // "4" stdZeroMinute // "04" stdSecond // "5" stdZeroSecond // "05" stdLongYear = iota + stdNeedDate // "2006" stdYear // "06" stdPM = iota + stdNeedClock // "PM" stdpm // "pm" stdTZ = iota // "MST" stdISO8601TZ // "Z0700" // prints Z for UTC stdISO8601SecondsTZ // "Z070000" stdISO8601ShortTZ // "Z07" stdISO8601ColonTZ // "Z07:00" // prints Z for UTC stdISO8601ColonSecondsTZ // "Z07:00:00" stdNumTZ // "-0700" // always numeric stdNumSecondsTz // "-070000" stdNumShortTZ // "-07" // always numeric stdNumColonTZ // "-07:00" // always numeric stdNumColonSecondsTZ // "-07:00:00" stdFracSecond0 // ".0", ".00", ... , trailing zeros included stdFracSecond9 // ".9", ".99", ..., trailing zeros omitted stdNeedDate = 1 << 8 // need month, day, year stdNeedClock = 2 << 8 // need hour, minute, second stdArgShift = 16 // extra argument in high bits, above low stdArgShift stdSeparatorShift = 28 // extra argument in high 4 bits for fractional second separators stdMask = 1<<stdArgShift - 1 // mask out argument )
所以,其實答案已經(jīng)有了,我們對照一下我們的參數(shù) 2006-01-02 15:04:05
,可以很簡單在上述常量里面找到對應(yīng)的常量:
2006
=>stdLongYear
01
=>stdZeroMonth
02
=>stdZeroDay
15
=>stdHour
04
=>stdZeroMinute
05
=>stdZeroSecond
而 layout
參數(shù)里面的 -
以及 :
都會原樣輸出。
根據(jù)給出的這些常量,我們就可以將時間格式化為我們想要的格式了。
到此這篇關(guān)于提升編程技能:學(xué)習(xí)如何在Go語言中正確格式化時間的文章就介紹到這了,更多相關(guān)go 格式化時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang gopm get -g -v 無法獲取第三方庫的解決方案
這篇文章主要介紹了golang gopm get -g -v 無法獲取第三方庫的解決方案,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05