// Copyright (c) 2015 qianqiusoft.com // Licensed to You under the GNU Affero GPL v3 // See the LICENSE file at git.qianqiusoft.com/qianqiusoft/light-vocation/LICENSE // http://www.gnu.org/licenses/why-affero-gpl.en.html package models import ( "fmt" "strings" "time" ) // datetime values like 2006-01-02 15:04:05 type LocalDate time.Time const formatDate = "2006-01-02" const nilDateStr = "0001-01-01" func CurrentDate() LocalDate { now := time.Now() nowStr := now.Format(formatDateTime) nowStr = strings.TrimSpace(nowStr) if len(nowStr) > 10 { nowStr = nowStr[0:10] } now, _ = timeParse(nowStr, formatDate) //time.ParseInLocation(formatDate, nowStr, time.Local) return LocalDate(now) } func nilDate() LocalDate { nilDate, _ := timeParse(nilDateStr, formatDate) //time.ParseInLocation(formatDate, nilDateStr, time.Local) return LocalDate(nilDate) } func isNilDate(tval time.Time) bool { return tval.Format(formatDate) == nilDateStr } // Value return the time.Time func (e LocalDate) IsNilDate() bool { return isNilDate(e.Value()) } // Value return the time.Time func (e LocalDate) Value() time.Time { return time.Time(e) } // Set set the LocalDate's value func (e *LocalDate) Set(d time.Time) { *e = LocalDate(d) } // String convert datatime to string func (e *LocalDate) String() string { return e.Value().String() } // FieldType return enum type Date //func (e *LocalDate) FieldType() int { // return orm.TypeDateField //} // SetRaw convert the interface to time.Time. Allow string and time.Time func (e *LocalDate) SetRaw(value interface{}) error { if value == nil { *e = nilDate() return nil } switch d := value.(type) { case time.Time: if isNilDate(d) { *e = nilDate() } else { e.Set(d) } case string: v, err := timeParse(d, formatDate) if err == nil { e.Set(v) } return err default: return fmt.Errorf(" unknown value `%s`", value) } return nil } // RawValue return Date value func (e *LocalDate) RawValue() interface{} { return e.Value() } func (t *LocalDate) UnmarshalJSON(data []byte) (err error) { if data[0] == '"' && data[len(data)-1] == '"' { data = data[1 : len(data)-1] } dataStr := strings.TrimSpace(string(data)) if dataStr == "" { *t = nilDate() return nil } if len(dataStr) > 10 { if dataStr == "0000-00-00 00:00:00" { dataStr = nilDateStr } else { dataStr = dataStr[0:10] } } now, err := timeParse(dataStr, formatDate) // time.ParseInLocation(formatDate, dataStr, time.Local) *t = LocalDate(now) return } func (t LocalDate) MarshalJSON() ([]byte, error) { if isNilDate(t.Value()) { return []byte{'"', '"'}, nil } b := make([]byte, 0, len(formatDate)+2) b = append(b, '"') b = append(b, []byte(time.Time(t).Format(formatDate))...) b = append(b, '"') return b, nil } //var _ orm.Fielder = new(LocalDate)