i have some problems creating a own type Date based on type time.Time
i tried to create the Date type as follows:
type Date time.Time
func (d Date) UnmarshalJSON(buf []byte) error {
var s string
json.Unmarshal(buf, &s)
t, err := time.Parse(timeLayout,s)
d= Date(t)
return err
}
func (d Date) MarshalJSON() ([]byte, error) {
b,_ := json.Marshal(d.Format(timeLayout))
return b,nil
}
this itself works, i can store this Date as a time.Time in AppEngine Datastore. the marshaling itself also works, but is not working is: then when unmarshal from json, the Date d is filled with the value. this is, as i understand right, because the unmarshalJson function create a copy of Date.
so when i change the unmarshalJson function to use a Pointer to Date then i cant use:
d=Date(t)
so first question, is there a solution how todo this ?
what i have done now is to rewrite the Code as follows:
type Date struct {
t time.Time
}
func (d *Date) UnmarshalJSON(buf []byte) error {
var s string
json.Unmarshal(buf, &s)
t, err := time.Parse(timeLayout,s)
d.t = t
return err
}
func (d Date) MarshalJSON() ([]byte, error) {
b,_ := json.Marshal(d.t.Format(timeLayout))
return b,nil
}
this works, but in this case Date is not an extending type of time.Time its just a wrapper to a time.Time type.
is there a better solution todo this ? im still new to go.
i need this Date type, to have a Date only json formated type, because Chrome only supports the html5 type: date and not datetime. and method overriding is not possible in go (means to override the un/marshalJson methods of type time.Time ) ?
thanks