Created
October 20, 2017 02:14
-
-
Save inlinechan/3869ad4dddaafa70fbfd93628c6f6178 to your computer and use it in GitHub Desktop.
This file contains 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
// 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