time.Time.MarshalText() Function in Golang with Examples
Last Updated :
28 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The MarshalText() function in Go language is used to implement the encoding.TextMarshaler interface. And the time here is formatted in RFC 3339 format along with the sub-second precision attached if available. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) MarshalText() ([]byte, error)
Here, “t” is the stated time and two values of type “byte” and “error” are returned as output in this method.
Return value: It returns a byte slice that represents receiver’s encoding into UTF-8-encoded text and it also returns an error occurred but if there are no errors then “nil” is returned.
Example 1:
package main
import "fmt"
import "time"
func main() {
t := time .Date(2001, 3, 6, 11, 45, 12, 03, time .UTC)
encoding, error := t.MarshalText()
fmt.Printf( "Receiver's encoding: %v\n" , encoding)
fmt.Printf( "Error occurred: %v\n" , error)
}
|
Output:
Receiver’s encoding: [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 occurred: <nil>
Example 2:
package main
import "fmt"
import "time"
func main() {
t := time .Date(2022, 67, 45, 89, 78, 90, 4353, time .UTC)
encoding, error := t.MarshalText()
fmt.Printf( "Receiver's encoding: %v\n" , encoding)
fmt.Printf( "Error occurred: %v\n" , error)
}
|
Output:
Receiver’s encoding: [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 occurred: <nil>
Here, the “t” stated in the above code has values that are outside the usual range but they are normalized while conversion.
Share your thoughts in the comments
Please Login to comment...