Golang time.Time.UnmarshalText()函数及示例
在Go语言中,time包提供了确定和查看时间的功能。在Go语言中, UnmarshalText() 函数用于实现encoding.TextUnmarshaler接口。这里的时间是RFC 3339格式的带引号字符串。此外,该函数定义在time包下。因此,你需要导入“time”包才能使用这些函数。
语法:
func (t *Time) UnmarshalText(data []byte) error
这里,“t”是指向指定时间的指针,“data”是表示由MarshalText()方法生成的表单编码的字节切片。
返回值:
它解码了由MarshalText()方法返回的编码,如果出现错误,则返回错误,否则返回“nil”。
示例1:
// Golang program to illustrate the usage of
// Time.UnmarshalText() function
// Including main package
package main
// Importing fmt and time
import "fmt"
import "time"
// Calling main
func main() {
// Defining t for MarshalText method
t := time.Date(2014, 5, 3, 13, 9, 7, 64, time.UTC)
// Calling MarshalText() method
encoding, _ := t.MarshalText()
// Defining tm for UnmarshalText() method
var tm time.Time
// Calling UnmarshalText method with its parameters
decode := tm.UnmarshalText(encoding)
// Prints output
fmt.Printf("Error: %v\n", decode)
}
输出:
Error: <nil>
示例2:
// Golang program to illustrate the usage of
// Time.UnmarshalText() function
// Including main package
package main
// Importing fmt and time
import "fmt"
import "time"
// Calling main
func main() {
// Defining t for MarshalText method
t := time.Date(2024, 85, 93, 103, 79, 97, 1264, time.UTC)
// Calling MarshalText() method
encoding, _ := t.MarshalText()
// Defining tm for UnmarshalText() method
var tm time.Time
// Calling UnmarshalText method with its parameters
decode := tm.UnmarshalText(encoding)
// Prints output
fmt.Printf("Error: %v\n", decode)
}
输出:
Error: <nil>
这里,“t”中的值超出了正常范围,但在转换时被规范化。