Home > Backend Development > Golang > How Can I Customize Timestamp Formatting in Go's JSON Output?

How Can I Customize Timestamp Formatting in Go's JSON Output?

DDD
Release: 2025-01-03 06:41:39
Original
900 people have browsed it

How Can I Customize Timestamp Formatting in Go's JSON Output?

Formatting Timestamps in Outgoing JSON with Custom Types

To format timestamps during JSON encoding, you can create a custom type that implements the Marshaler interface. By doing so, you gain control over the serialization process, allowing you to specify the desired format.

Implementing the Marshaler Interface

The Marshaler interface requires a single method, MarshalJSON, which returns a byte slice representing the JSON-encoded data and an error if any. In this case, you'll define a custom type that wraps time.Time and implements MarshalJSON.

Here's an example implementation:

type JSONTime time.Time

func (t JSONTime)MarshalJSON() ([]byte, error) {
    // Format the timestamp in the desired format
    stamp := fmt.Sprintf("\"%s\"", time.Time(t).Format("Mon Jan _2"))
    return []byte(stamp), nil
}
Copy after login

Updating the Document Struct

In your Document struct, replace time.Time with the custom JSONTime type for the Stamp field:

type Document struct {
    Name        string
    Content     string
    Stamp       JSONTime
    Author      string
}
Copy after login

Initializing the Document

When initializing the Document instance, use JSONTime(time.Now()) instead of time.Now():

testDoc := model.Document{"Meeting Notes", "These are some notes", JSONTime(time.Now()), "Bacon"}
Copy after login

By following these steps, you can format timestamps in your JSON responses according to your requirements. You can extend this concept to other custom types or scenarios as needed.

The above is the detailed content of How Can I Customize Timestamp Formatting in Go's JSON Output?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template