diff options
author | Brian Picciano <mediocregopher@gmail.com> | 2022-05-06 17:22:17 -0600 |
---|---|---|
committer | Brian Picciano <mediocregopher@gmail.com> | 2022-05-06 17:22:21 -0600 |
commit | f7d72adfb594980b0442c0fa7b5586e6248f96ac (patch) | |
tree | 05f3e80c1f8fc79b3ae67f886534681ddc8c0b62 /srv/src/post/date.go | |
parent | d8b12cf17a43e700d841402f712efa8666e6137f (diff) |
Implement post.Store
Diffstat (limited to 'srv/src/post/date.go')
-rw-r--r-- | srv/src/post/date.go | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/srv/src/post/date.go b/srv/src/post/date.go new file mode 100644 index 0000000..34fe109 --- /dev/null +++ b/srv/src/post/date.go @@ -0,0 +1,59 @@ +package post + +import ( + "database/sql/driver" + "fmt" + "time" +) + +// Date represents a calendar date with no timezone information attached. +type Date struct { + Year int + Month time.Month + Day int +} + +// DateFromTime converts a Time into a Date, truncating all non-date +// information. +func DateFromTime(t time.Time) Date { + t = t.UTC() + return Date{ + Year: t.Year(), + Month: t.Month(), + Day: t.Day(), + } +} + +// ToTime converts a Date into a Time. The returned time will be UTC midnight of +// the Date. +func (d *Date) ToTime() time.Time { + return time.Date(d.Year, d.Month, d.Day, 0, 0, 0, 0, time.UTC) +} + +// Scan implements the sql.Scanner interface. +func (d *Date) Scan(src interface{}) error { + + if src == nil { + *d = Date{} + return nil + } + + ts, ok := src.(int64) + + if !ok { + return fmt.Errorf("cannot scan value %#v into Date", src) + } + + *d = DateFromTime(time.Unix(ts, 0)) + return nil +} + +// Value implements the driver.Valuer interface. +func (d Date) Value() (driver.Value, error) { + + if d == (Date{}) { + return nil, nil + } + + return d.ToTime().Unix(), nil +} |