在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的Parse()函數用於解析格式化的字符串,然後查找它形成的時間值。此外,此函數在時間包下定義。在這裏,您需要導入“time”軟件包才能使用這些函數。
用法:
func Parse(layout, value string) (Time, error)
在這裏,layout通過以哪種方式顯示參考時間(即定義為Mon Jan 2 15:04:05 -0700 MST 2006)來指定格式,如果它是該值的話。但是,先前定義的布局(例如UnixDate,ANSIC,RFC3339等)解釋了標準時間以及參考時間的合適表示形式。並且value參數保存字符串。其中,從值中刪除的元素假定為零,如果不可能為零,則假定為一。
返回值:它返回它表示的時間值。並且如果不存在時區指示符,則它會返回UTC時間。
範例1:
// Golang program to illustrate the usage of
// time.Parse() function
// Including main package
package main
// Importing fmt and time
import "fmt"
import "time"
// Calling main
func main() {
// Declaring layout constant
const layout = "Jan 2, 2006 at 3:04pm (MST)"
// Calling Parse() method with its parameters
tm, _:= time.Parse(layout, "Feb 4, 2014 at 6:05pm (PST)")
// Returns output
fmt.Println(tm)
}
輸出:
2014-02-04 18:05:00 +0000 PST
在此,返回的輸出在PST中,如上麵所定義,並且此處使用的布局常數和值是其long-form。
範例2:
// Golang program to illustrate the usage of
// time.Parse() function
// Including main package
package main
// Importing fmt and time
import "fmt"
import "time"
// Calling main
func main() {
// Declaring layout constant
const layout = "2006-Jan-02"
// Calling Parse() method with its parameters
tm, _:= time.Parse(layout, "2014-Feb-04")
// Returns output
fmt.Println(tm)
}
輸出:
2014-02-04 00:00:00 +0000 UTC
在這裏,返回的輸出以UTC表示,因為沒有時區指示符,並且此處使用的布局常量和值是其簡短形式。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 time.Parse() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。