Created
October 21, 2020 11:50
-
-
Save akhrszk/8ae5be4df99ecd8956ab07d22841ec2e to your computer and use it in GitHub Desktop.
unix timestamp in Golang
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
// marshal/unmarshal to/from unix timestamp | |
// implement the Scanner and Valuer interfaces of gorm (https://gorm.io/docs/data_types.html) | |
package custom | |
import ( | |
"time" | |
"fmt" | |
"strconv" | |
"database/sql/driver" | |
) | |
type Timestamp time.Time | |
func (t *Timestamp) MarshalJSON() ([]byte, error) { | |
unixTimestamp := fmt.Sprintf("\"%d\"", time.Time(*t).Unix()) | |
return []byte(unixTimestamp), nil | |
} | |
func (t *Timestamp) UnmarshalJSON(data []byte) error { | |
unixTimestamp, err := strconv.ParseInt(string(data), 10, 64) | |
if err != nil { | |
return err | |
} | |
*t = Timestamp(time.Unix(unixTimestamp, 0)) | |
return nil | |
} | |
func (t *Timestamp) Scan(value interface{}) error { | |
time, ok := value.(time.Time) | |
if ok { | |
*t = Timestamp(time) | |
} | |
return nil | |
} | |
func (t Timestamp) Value() (driver.Value, error) { | |
return time.Time(t), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment