Golang time.Time.MarshalText() 函数及示例

Golang time.Time.MarshalText() 函数及示例

Go 语言中,time 包提供了确定和查看时间的功能。Go 语言中的 MarshalText() 函数用于实现 encoding.TextMarshaler 接口。此处的时间格式为 RFC 3339,如果可用,则附加亚秒精度。此函数也是在 time 包下定义的。您需要导入 “time” 包以使用这些函数。

语法:

func (t Time) MarshalText() ([]byte, error)

这里,“t” 是指定的时间,并在此方法中返回两个值:类型为“byte”和“error”的两个值。

返回值: 它返回一个字节切片,表示收件人的编码为 UTF-8 编码的文本,并在发生错误时返回一个错误,但如果没有错误,则返回“nil”。

示例1:

// Go 语言程序示例,演示
// Time.MarshalText() 函数的用法
  
// 包括主要程序
package main
  
// 导入 fmt 和 time 包
import "fmt"
import "time"
  
// 调用 main 函数
func main() {
  
    //为 MarshalText 方法定义 t
    t := time.Date(2001, 3, 6, 11, 45, 12, 03, time.UTC)
  
    // 调用 MarshalText() 方法
    encoding, error := t.MarshalText()
  
    // 输出接收者的编码
    fmt.Printf("接收者的编码: %v\n", encoding)
  
    // 输出错误
    fmt.Printf("发生错误: %v\n", error)
} 

输出:

接收者的编码: [50 48 48 49 45 48 51 45 48 54 84 49 49 58 52 53 58 49 50 46 48 48 48 48 48 48 48 48 51 90]
发生错误:

示例2:

// Go 语言程序示例,演示
// Time.MarshalText() 函数的用法
  
// 包括主要程序
package main
  
// 导入 fmt 和 time 包
import "fmt"
import "time"
  
// 调用 main 函数
func main() {
  
    //为 MarshalText 方法定义 t
    t := time.Date(2022, 67, 45, 89, 78, 90, 4353, time.UTC)
  
    // 调用 MarshalText() 方法
    encoding, error := t.MarshalText()
  
    // 输出接收者的编码
    fmt.Printf("接收者的编码: %v\n", encoding)
  
    // 输出错误
    fmt.Printf("发生错误: %v\n", error)
} 

输出:

接收者的编码: [50 48 50 55 45 48 56 45 49 55 84 49 56 58 49 57 58 51 48 46 48 48 48 48 48 52 51 53 51 90]
发生错误:

在上面的代码中,所述的“t”具有超出常规范围的值,但在转换时进行了标准化。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程