📜  Golang 中的 time.Parse()函数示例

📅  最后修改于: 2021-10-24 14:05:38             🧑  作者: Mango

在 Go 语言中,时间包提供了确定和查看时间的功能。 Go 语言中的Parse()函数用于解析格式化的字符串,然后找到它形成的时间值。而且,这个函数是在time包下定义的。在这里,您需要导入“time”包才能使用这些功能。

句法:

func Parse(layout, value string) (Time, error)

在这里,布局通过以何种方式显示参考时间来指定格式,即定义为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 中,这里使用的布局常量和值是它的长格式。

示例 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 格式,因为没有时区指示器,并且此处使用的布局常量和值是它的缩写形式。