Skip to content

Instantly share code, notes, and snippets.

@darmawan01
Created December 22, 2022 13:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darmawan01/7015a5dde4d792f6dfc186aee7e94d24 to your computer and use it in GitHub Desktop.
Save darmawan01/7015a5dde4d792f6dfc186aee7e94d24 to your computer and use it in GitHub Desktop.
Custom Time Marshal/Unmarshal from unix milisecond
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