Skip to content

Instantly share code, notes, and snippets.



Last active Jun 15, 2018
What would you like to do?
Go date.Date
package date
import (
// DateFormat is date format
const DateFormat = "2006-01-02"
// Date is date time
type Date struct {
time time.Time
// Now is get today
func Now() Date {
return Date{
time: time.Now(),
func (d Date) String() string {
y, m, day := d.time.Date()
return fmt.Sprintf("%04d-%02d-%02d", y, m, day)
// Value is implement database/sql/driver
func (d Date) Value() (driver.Value, error) {
return d.time, nil
// Scan is implement database/sql/driver
func (d *Date) Scan(src interface{}) error {
source, ok := src.(time.Time)
if !ok {
return errors.New("Incompatible type for Date")
d.time = source
return nil
// UnmarshalJSON - implement Unmarshaler
func (d *Date) UnmarshalJSON(b []byte) error {
var tmp string
err := json.Unmarshal(b, &tmp)
if err != nil {
return err
d.time, err = time.Parse(DateFormat, tmp)
if err != nil {
return err
return nil
// MarshalJSON - implement Marshaler
func (d *Date) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%v"`, d.String())), nil
// After reports whether the date instant t is after u.
func (d Date) After(u Date) bool {
return d.time.After(u.time)
// Before reports whether the date instant t is before u.
func (d Date) Before(u Date) bool {
return d.time.Before(u.time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.