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:
// Golang program to illustrate the usage of // Time.MarshalBinary() function // Including main package package main // Importing fmt and time import "fmt" import " time "
// Calling main func main() { // Defining t for MarshalBinary method
t := time .Date(2001, 2, 1, 14, 30, 12, 05, time .UTC)
// Calling MarshalBinary() method
encoding, error := t.MarshalBinary()
// Prints receiver's encoding
fmt.Printf("Receiver's encoding: %v\n", encoding)
// Prints error
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:
// Golang program to illustrate the usage of // Time.MarshalBinary() function // Including main package package main // Importing fmt and time import "fmt" import " time "
// Calling main func main() { // Defining t for MarshalBinary method
t := time .Date(2021, 45, 56, 34, 76, 92, 66565, time .UTC)
// Calling MarshalBinary() method
encoding, error := t.MarshalBinary()
// Prints receiver's encoding
fmt.Printf("Receiver's encoding: %v\n", encoding)
// Prints error
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.