2019-09-07 22:23:42 +03:00
|
|
|
// For more tutorials: https://blog.learngoprogramming.com
|
|
|
|
//
|
|
|
|
// Copyright © 2018 Inanc Gumus
|
|
|
|
// Learn Go Programming Course
|
|
|
|
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
|
|
|
//
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2019-10-15 13:30:43 +03:00
|
|
|
type timestamp struct {
|
|
|
|
time.Time
|
2019-09-07 22:23:42 +03:00
|
|
|
}
|
|
|
|
|
2019-10-15 13:30:43 +03:00
|
|
|
// timestamp knows how to decode itself from json.
|
|
|
|
//
|
|
|
|
// UnmarshalJSON is an implementation of the json.Unmarshaler interface.
|
|
|
|
// json.Unmarshal and json.Decode call this method.
|
2019-09-07 22:23:42 +03:00
|
|
|
func (ts *timestamp) UnmarshalJSON(data []byte) error {
|
2019-10-15 13:30:43 +03:00
|
|
|
*ts = toTimestamp(string(data))
|
2019-09-07 22:23:42 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-10-15 13:30:43 +03:00
|
|
|
// timestamp knows how to encode itself to json.
|
|
|
|
//
|
|
|
|
// MarshalJSON is an implementation of the json.Marshaler interface.
|
|
|
|
// json.Marshal and json.Encode call this method.
|
|
|
|
func (ts timestamp) MarshalJSON() (out []byte, err error) {
|
|
|
|
return strconv.AppendInt(out, ts.Unix(), 10), nil
|
|
|
|
}
|
2019-09-07 22:23:42 +03:00
|
|
|
|
2019-10-15 13:30:43 +03:00
|
|
|
func (ts timestamp) String() string {
|
|
|
|
if ts.IsZero() {
|
2019-09-07 22:23:42 +03:00
|
|
|
return "unknown"
|
|
|
|
}
|
|
|
|
|
2019-09-27 19:09:07 +03:00
|
|
|
// Mon Jan 2 15:04:05 -0700 MST 2006
|
|
|
|
const layout = "2006/01"
|
2019-10-15 13:30:43 +03:00
|
|
|
return ts.Format(layout)
|
2019-09-07 22:23:42 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func toTimestamp(v interface{}) timestamp {
|
|
|
|
var t int
|
|
|
|
|
|
|
|
switch v := v.(type) {
|
|
|
|
case int:
|
2019-10-15 13:30:43 +03:00
|
|
|
// book{title: "moby dick", price: 10, published: 118281600},
|
2019-09-07 22:23:42 +03:00
|
|
|
t = v
|
|
|
|
case string:
|
2019-10-15 13:30:43 +03:00
|
|
|
// book{title: "odyssey", price: 15, published: "733622400"},
|
2019-09-07 22:23:42 +03:00
|
|
|
t, _ = strconv.Atoi(v)
|
|
|
|
default:
|
2019-10-15 13:30:43 +03:00
|
|
|
// book{title: "hobbit", price: 25},
|
|
|
|
return timestamp{}
|
2019-09-07 22:23:42 +03:00
|
|
|
}
|
|
|
|
|
2019-10-15 13:30:43 +03:00
|
|
|
return timestamp{
|
|
|
|
Time: time.Unix(int64(t), 0),
|
|
|
|
}
|
2019-09-07 22:23:42 +03:00
|
|
|
}
|