Created
December 22, 2022 13:06
-
-
Save darmawan01/7015a5dde4d792f6dfc186aee7e94d24 to your computer and use it in GitHub Desktop.
Custom Time Marshal/Unmarshal from unix milisecond
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
package types | |
import ( | |
"database/sql/driver" | |
"fmt" | |
"strconv" | |
"strings" | |
"time" | |
) | |
type Time time.Time | |
func (t Time) MarshalJSON() ([]byte, error) { | |
return []byte(strconv.FormatInt(time.Time(t).UnixMilli(), 10)), nil | |
} | |
func (t *Time) UnmarshalJSON(s []byte) (err error) { | |
r := strings.Replace(string(s), `"`, ``, -1) | |
q, err := strconv.ParseInt(r, 10, 64) | |
if err != nil { | |
return err | |
} | |
*(*time.Time)(t) = time.Unix(0, q*int64(time.Millisecond)) | |
return | |
} | |
func (t Time) String() string { return time.Time(t).String() } | |
func (t *Time) Scan(value interface{}) error { | |
switch v := value.(type) { | |
case time.Time: | |
*t = Time(v) | |
case nil: | |
*t = Time{} | |
default: | |
return fmt.Errorf("cannot sql.Scan() Time from: %#v", v) | |
} | |
return nil | |
} | |
func (t Time) Value() (driver.Value, error) { | |
return driver.Value(time.Time(t)), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment