En el lenguaje Go, los paquetes de tiempo brindan funcionalidad para determinar y ver el tiempo. La función MarshalText() en el lenguaje Go se usa para implementar la interfaz encoding.TextMarshaler . Y el tiempo aquí está formateado en formato RFC 3339 junto con la precisión de subsegundo adjunta si está disponible. Además, esta función se define en el paquete de tiempo. Aquí, debe importar el paquete «tiempo» para usar estas funciones.
Sintaxis:
func (t Time) MarshalText() ([]byte, error)
Aquí, «t» es el tiempo indicado y dos valores de tipo «byte» y «error» se devuelven como salida en este método.
Valor de retorno: devuelve un segmento de bytes que representa la codificación del receptor en texto codificado en UTF-8 y también devuelve un error, pero si no hay errores, se devuelve «nil».
Ejemplo 1:
// Golang program to illustrate the usage of // Time.MarshalText() 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(2001, 3, 6, 11, 45, 12, 03, time.UTC) // Calling MarshalText() method encoding, error := t.MarshalText() // Prints receiver's encoding fmt.Printf("Receiver's encoding: %v\n", encoding) // Prints error fmt.Printf("Error occurred: %v\n", error) }
Producción:
Codificación del receptor: [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]
Error ocurrido: <nil>
Ejemplo 2:
// Golang program to illustrate the usage of // Time.MarshalText() 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(2022, 67, 45, 89, 78, 90, 4353, time.UTC) // Calling MarshalText() method encoding, error := t.MarshalText() // Prints receiver's encoding fmt.Printf("Receiver's encoding: %v\n", encoding) // Prints error fmt.Printf("Error occurred: %v\n", error) }
Producción:
Codificación del receptor: [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]
Error ocurrido: <nil>
Aquí, la «t» indicada en el código anterior tiene valores que están fuera del rango habitual pero se normalizan durante la conversión.
Publicación traducida automáticamente
Artículo escrito por nidhi1352singh y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA