time.Time.MarshalBinary() Function in Golang with Examples
Last Updated :
06 Jul, 2022
In Go language, time packages supplies functionality for determining as well as viewing time. The MarshalBinary() function in Go language is used to implement the encoding.BinaryMarshaler interface. 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) MarshalBinary() ([]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 the encoding of the receiver into a binary form and also returns an error occurred but if there are no errors then “nil” is returned.
Example 1:
C
package main
import "fmt"
import " time "
func main() {
t := time .Date(2001, 2, 1, 14, 30, 12, 05, time .UTC)
encoding, error := t.MarshalBinary()
fmt.Printf("Receiver's encoding: %v\n", encoding)
fmt.Printf("Error occurred: %v\n", error)
}
|
Output:
Receiver's encoding: [1 0 0 0 14 178 11 105 244 0 0 0 5 255 255]
Error occurred: nil
Example 2:
C
package main
import "fmt"
import " time "
func main() {
t := time .Date(2021, 45, 56, 34, 76, 92, 66565, time .UTC)
encoding, error := t.MarshalBinary()
fmt.Printf("Receiver's encoding: %v\n", encoding)
fmt.Printf("Error occurred: %v\n", error)
}
|
Output:
Receiver's encoding: [1 0 0 0 14 222 176 24 76 0 1 4 5 255 255]
Error occurred: nil
Here, the “t” stated in the above code has values that are outside usual range but they are normalized while conversion.
Share your thoughts in the comments
Please Login to comment...