Home > Backend Development > Golang > How to Customize Timestamp Formatting in Go's JSON Encoding?

How to Customize Timestamp Formatting in Go's JSON Encoding?

Patricia Arquette
Release: 2024-12-19 05:51:36
Original
135 people have browsed it

How to Customize Timestamp Formatting in Go's JSON Encoding?

Formatting Timestamps for JSON Encoding

When working with Go, one might encounter a need to format timestamps outputted by the time.Time type. By default, JSON marshals time as RFC3339, resulting in an undesirable format.

Customizing Timestamp Formatting

To customize timestamp formatting, implement the Marshaler interface for your custom time type:

import (
    "encoding/json"
    "fmt"
)

type JSONTime time.Time

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

Apply this custom type to your Document struct:

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

When marshaling, you can then initialize the Document instance as:

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

The resultant JSON will now have a formatted timestamp in your desired format, such as "May 15, 2014".

The above is the detailed content of How to Customize Timestamp Formatting in Go's JSON Encoding?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template