Open In App

time.Time.MarshalJSON() Function in Golang with Examples

Last Updated : 28 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In Go language, time packages supplies functionality for determining as well as viewing time. The MarshalJSON() function in Go language is used to implement the json.Marshaler interface. And the time here is a quoted-string which is 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) MarshalJSON() ([]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 JSON encoding and it 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.MarshalJSON() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Defining t for MarshalJSON method
    t := time.Date(2014, 11, 10, 14, 30, 12, 05, time.UTC)
  
    // Calling MarshalJSON() method
    encoding, error := t.MarshalJSON()
  
    // Prints JSON's encoding
    fmt.Printf("JSON's encoding: %v\n", encoding)
  
    // Prints error
    fmt.Printf("Error occurred: %v\n", error)
}


Output:

JSON’s encoding: [34 50 48 49 52 45 49 49 45 49 48 84 49 52 58 51 48 58 49 50 46 48 48 48 48 48 48 48 48 53 90 34]
Error occurred: <nil>

Example 2:




// Golang program to illustrate the usage of
// Time.MarshalJSON() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Defining t for MarshalJSON method
    t := time.Date(2022, 45, 67, 88, 67, 76, 903, time.UTC)
  
    // Calling MarshalJSON() method
    encoding, error := t.MarshalJSON()
  
    // Prints JSON's encoding
    fmt.Printf("JSON's encoding: %v\n", encoding)
  
    // Prints error
    fmt.Printf("Error occurred: %v\n", error)
}


Output:

JSON’s encoding: [34 50 48 50 53 45 49 49 45 48 57 84 49 55 58 48 56 58 49 54 46 48 48 48 48 48 48 57 48 51 90 34]
Error occurred: <nil>

Here, the “t” stated in the above code has values that are outside usual range but they are normalized while conversion.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads