Browse Source

fix types datetime

ls 2 years ago
parent
commit
de975e2d3d
1 changed files with 25 additions and 36 deletions
  1. 25 36
      types/datetime.go

+ 25 - 36
types/datetime.go

@@ -6,63 +6,52 @@ import (
 	"time"
 )
 
-// DateText is an implementation of a string for the MySQL type date.
-type DateText string
-
-// TimeText is an implementation of a string for the MySQL type datetime.
+// TimeText time text
 type TimeText string
 
+// DateText date text
+type DateText string
+
+// const
 const (
-	formtDate = `2006-01-02`
-	formtTime = `2006-01-02 15:04:05`
+	timeFormat = `2006-01-02 15:04:05`
+	dateFormat = `2006-01-02`
 )
 
-// Value implements the driver.Valuer interface,
-// and turns the date into a DateText (date) for MySQL storage.
-func (d DateText) Value() (driver.Value, error) {
-	t, err := time.Parse(formtDate, string(d))
+// Value implements the driver.Valuer interface
+func (t TimeText) Value() (driver.Value, error) {
+	t1, err := time.ParseInLocation(timeFormat, string(t), time.Local)
 	if err != nil {
 		return nil, err
 	}
-	return DateText(t.Format(formtDate)), nil
+	return TimeText(t1.Format(timeFormat)), nil
 }
 
-// Scan implements the sql.Scanner interface,
-// and turns the bitfield incoming from MySQL into a Date
-func (d *DateText) Scan(src interface{}) error {
-	v, ok := src.([]byte)
+// Scan implements the sql.Scanner interface
+func (t *TimeText) Scan(src interface{}) error {
+	v, ok := src.(time.Time)
 	if !ok {
-		return errors.New("bad []byte type assertion")
+		return errors.New("bad time.Time type assertion")
 	}
-	t, err := time.Parse(formtDate, string(v))
-	if err != nil {
-		return err
-	}
-	*d = DateText(t.Format(formtDate))
+	*t = TimeText(v.Format(timeFormat))
 	return nil
 }
 
-// Value implements the driver.Valuer interface,
-// and turns the date into a DateText (date) for MySQL storage.
-func (d TimeText) Value() (driver.Value, error) {
-	t, err := time.Parse(formtDate, string(d))
+// Value implements the driver.Valuer interface
+func (t DateText) Value() (driver.Value, error) {
+	t1, err := time.ParseInLocation(dateFormat, string(t), time.Local)
 	if err != nil {
 		return nil, err
 	}
-	return TimeText(t.Format(formtTime)), nil
+	return DateText(t1.Format(dateFormat)), nil
 }
 
-// Scan implements the sql.Scanner interface,
-// and turns the bitfield incoming from MySQL into a Date
-func (d *TimeText) Scan(src interface{}) error {
-	v, ok := src.([]byte)
+// Scan implements the sql.Scanner interface
+func (t *DateText) Scan(src interface{}) error {
+	v, ok := src.(time.Time)
 	if !ok {
-		return errors.New("bad []byte type assertion")
-	}
-	t, err := time.Parse(formtDate, string(v))
-	if err != nil {
-		return err
+		return errors.New("bad time.Time type assertion")
 	}
-	*d = TimeText(t.Format(formtTime))
+	*t = DateText(v.Format(dateFormat))
 	return nil
 }