Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. package utime
  2.  
  3. import (
  4. "database/sql/driver"
  5. "encoding/json"
  6. "fmt"
  7. "strings"
  8. "time"
  9. )
  10.  
  11. type UnixTime struct {
  12. Utime int64
  13. Valid bool // Valid is true if Time is not NULL
  14. }
  15.  
  16. func NewUnixTime(t time.Time) UnixTime {
  17. return UnixTime{
  18. Utime: t.Unix(),
  19. Valid: true,
  20. }
  21. }
  22.  
  23. func (nt *UnixTime) Scan(value interface{}) error {
  24. var err error
  25. switch x := value.(type) {
  26. case time.Time:
  27. nt.Utime = x.Unix()
  28. fmt.Println("Unixtime.Scan: found time.Time ") // debug
  29. case []uint8:
  30. tmpTime, err := time.Parse(time.RFC3339, string(x))
  31. if err != nil {
  32. // try parsing with time.RFC3339nano
  33. tmpTime, err = time.Parse(time.RFC3339Nano, string(x))
  34. if err != nil {
  35. nt.Valid = false
  36. return nil
  37. }
  38. }
  39. nt.Utime = tmpTime.Unix()
  40. fmt.Println("Unixtime.Scan: tmptime: ", tmpTime) // debug
  41. case nil:
  42. fmt.Println("Unixtime.Scan: tmptime is nil") // debug
  43. nt.Valid = false
  44. return nil
  45. default:
  46. err = fmt.Errorf("null: cannot scan type %T into UnixTime: %v", value, value)
  47. }
  48. nt.Valid = err == nil
  49. return err
  50. }
  51.  
  52. func (nt UnixTime) Value() (driver.Value, error) {
  53. if !nt.Valid {
  54. return nil, nil
  55. }
  56. return time.Unix(nt.Utime, 0), nil
  57. }
  58.  
  59. func (nt *UnixTime) String() string {
  60. if !nt.Valid {
  61. return ""
  62. }
  63. return time.Unix(nt.Utime, 0).Format(time.RFC3339)
  64. }
  65.  
  66. func (nt UnixTime) MarshalJSON() ([]byte, error) {
  67. return json.Marshal(strings.Replace(time.Unix(nt.Utime, 0).Format(time.RFC3339), "+", "Z", -1))
  68. }
  69.  
  70. func (nt *UnixTime) UnmarshalJSON(b []byte) (err error) {
  71. if b[0] == '"' && b[len(b)-1] == '"' {
  72. b = b[1 : len(b)-1]
  73. }
  74. tmpTime, err := time.Parse(time.RFC3339, string(b))
  75. if err != nil {
  76. nt.Valid = false
  77. return err
  78. }
  79. nt.Valid = true
  80. nt.Utime = tmpTime.Unix()
  81. return
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement