forked from free-lancers/electricity_bill_calc_service
		
	enhance(model):调整自定义的日期类型,以及相关的查询。
This commit is contained in:
		| @@ -19,10 +19,34 @@ func NewDate(t time.Time) Date { | ||||
| 	} | ||||
| 	t = t.In(loc) | ||||
| 	return Date{ | ||||
| 		Time: time.Date(0, 1, 1, t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), loc), | ||||
| 		Time: time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, loc), | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func NewEmptyDate() Date { | ||||
| 	loc, err := time.LoadLocation("Asia/Shanghai") | ||||
| 	if err != nil { | ||||
| 		panic(err) | ||||
| 	} | ||||
| 	return Date{ | ||||
| 		Time: time.Date(0, 1, 1, 0, 0, 0, 0, loc), | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func ParseDate(t string) (Date, error) { | ||||
| 	loc, err := time.LoadLocation("Asia/Shanghai") | ||||
| 	if err != nil { | ||||
| 		return NewEmptyDate(), fmt.Errorf("unable to load time zone, %w", err) | ||||
| 	} | ||||
| 	d, err := time.ParseInLocation("2006-01-02", t, loc) | ||||
| 	if err != nil { | ||||
| 		return NewEmptyDate(), fmt.Errorf("unable to parse given time, %w", err) | ||||
| 	} | ||||
| 	return Date{ | ||||
| 		Time: d, | ||||
| 	}, nil | ||||
| } | ||||
|  | ||||
| var _ driver.Valuer = (*Date)(nil) | ||||
|  | ||||
| func (d Date) Value() (driver.Value, error) { | ||||
| @@ -62,7 +86,7 @@ func (d *Date) Scan(src interface{}) (err error) { | ||||
| var _ json.Marshaler = (*Date)(nil) | ||||
|  | ||||
| func (d Date) MarshalJSON() ([]byte, error) { | ||||
| 	return []byte(d.Time.Format("2006-01-02")), nil | ||||
| 	return json.Marshal(d.Time.Format("2006-01-02")) | ||||
| } | ||||
|  | ||||
| var _ json.Unmarshaler = (*Date)(nil) | ||||
| @@ -72,7 +96,11 @@ func (d *Date) UnmarshalJSON(raw []byte) error { | ||||
| 	if err != nil { | ||||
| 		return fmt.Errorf("unable to load time zone, %w", err) | ||||
| 	} | ||||
| 	s := string(raw) | ||||
| 	var s string | ||||
| 	err = json.Unmarshal(raw, &s) | ||||
| 	if err != nil { | ||||
| 		return fmt.Errorf("unable to unmarshal value, %w", err) | ||||
| 	} | ||||
| 	d.Time, err = time.ParseInLocation("2006-01-02", s, loc) | ||||
| 	return err | ||||
| } | ||||
|   | ||||
		Reference in New Issue
	
	Block a user