I have a struct like so
type log struct {
[...]
Timestamp timestamp `json:"timestamp"`
}
and I want to have the Timestamp as unix timestamp instead of whatever go does by default (2018-09-21T19:31:03.291Z
)
I've tried creating a custom type for that like this:
type timestamp struct {
time.Time
}
func (t timestamp) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(time.Time(t.Time).Unix(), 10)), nil
}
func (t *timestamp) UnmarshalJSON(data []byte) error {
i, err := strconv.ParseInt(string(data[:]), 10, 64)
if err != nil {
return err
}
t = ×tamp{
time.Unix(i, 0),
}
return nil
}
but I'm always getting the error can not unmarshal timestamp into *main.timestamp
when trying to read from the database.
for iter.Scan(&message.Text, &message.Timestamp) {
userlogResult.Messages = append(userlogResult.Messages, message)
}
if err := iter.Close(); err != nil {
log.Error(err)
}
It can't unmarshall the Timestamp here. https://github.com/gocql/gocql/blob/799fb0373110eaa4e2e71dd32a9b5903f80dca8f/helpers.go#L30 the issue is that it doesn't use the Unmarshall functions.
Edit: I've answered my own question.
Copyright Notice:Content Author:「gempir」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/52464058/marshalling-time-time-to-unix-timestamp