Created
February 14, 2024 11:00
-
-
Save stalko/10db1a7a8e26e0e6b683beb854bb6591 to your computer and use it in GitHub Desktop.
GoLang CustomTime format with json Unmarshal and Marshal operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"strings" | |
"time" | |
) | |
type StructWithCustomTime struct { | |
MyTime CustomTime `json:"my_time"` | |
} | |
type CustomTime struct { | |
time.Time | |
} | |
const localTimeLayout = "2006-01-02 15:04" | |
func (ct *CustomTime) UnmarshalJSON(b []byte) (err error) { | |
s := strings.Trim(string(b), "\"") | |
if s == "null" { | |
ct.Time = time.Time{} | |
return | |
} | |
ct.Time, err = time.Parse(localTimeLayout, s) | |
return | |
} | |
func (ct CustomTime) MarshalJSON() ([]byte, error) { | |
stamp := fmt.Sprintf("\"%s\"", ct.Time.Format(localTimeLayout)) | |
return []byte(stamp), nil | |
} | |
func main() { | |
incomingJson := `{"my_time":"2020-01-01 12:00"}` | |
var s StructWithCustomTime | |
// Unmarshal the incoming JSON into a StructWithCustomTime | |
err := json.Unmarshal([]byte(incomingJson), &s) | |
if err != nil { | |
log.Printf("Error unmarshalling JSON: %v", err) | |
} | |
// Marshal the StructWithCustomTime back into JSON | |
outgoingJson, err := json.Marshal(s) | |
if err != nil { | |
log.Printf("Error marshalling JSON: %v", err) | |
} | |
fmt.Println(string(outgoingJson)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment