Skip to content

Instantly share code, notes, and snippets.

@inlinechan
Created October 20, 2017 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inlinechan/3869ad4dddaafa70fbfd93628c6f6178 to your computer and use it in GitHub Desktop.
Save inlinechan/3869ad4dddaafa70fbfd93628c6f6178 to your computer and use it in GitHub Desktop.
// UnmarshalJSON from string to time.Time
package main
import (
"encoding/json"
"fmt"
"time"
)
type Response struct {
Time CustomTime
}
type CustomTime struct {
time.Time
}
func (t *CustomTime) UnmarshalJSON(b []byte) error {
var timeString string
err := json.Unmarshal(b, &timeString)
if err != nil {
// fmt.Println(err.Error())
return err
}
// RFC3339 = "2006-01-02T15:04:05Z07:00"
t2, err := time.Parse("2006-01-02T15:04:05", timeString)
if err != nil {
// fmt.Println(err.Error())
return err
}
t.Time = t2
return nil
}
func main() {
data := []byte(`{"Time":"2017-10-20T00:00:00"}`)
res := new(Response)
err := json.Unmarshal(data, &res)
if err != nil {
fmt.Printf(err.Error())
} else {
fmt.Printf("%v\n", res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment