github.com/profzone/eden-framework@v1.0.10/pkg/timelib/mysql_datetime.go (about) 1 package timelib 2 3 import ( 4 "database/sql" 5 "database/sql/driver" 6 "encoding" 7 "fmt" 8 "time" 9 ) 10 11 var ( 12 MySQLDatetimeZero = MySQLDatetime(time.Time{}) 13 ) 14 15 // swagger:strfmt date-time 16 type MySQLDatetime time.Time 17 18 func ParseMySQLDatetimeFromString(s string) (dt MySQLDatetime, err error) { 19 var t time.Time 20 t, err = time.Parse(time.RFC3339, s) 21 dt = MySQLDatetime(t) 22 return 23 } 24 25 func ParseMySQLDatetimeFromStringWithFormatterInCST(s, formatter string) (dt MySQLDatetime, err error) { 26 var t time.Time 27 t, err = time.ParseInLocation(formatter, s, CST) 28 dt = MySQLDatetime(t) 29 return 30 } 31 32 var _ interface { 33 sql.Scanner 34 driver.Valuer 35 } = (*MySQLDatetime)(nil) 36 37 func (dt *MySQLDatetime) Scan(value interface{}) error { 38 switch v := value.(type) { 39 case time.Time: 40 *dt = MySQLDatetime(time.Unix(v.Unix(), 0)) 41 case nil: 42 *dt = MySQLDatetimeZero 43 default: 44 return fmt.Errorf("cannot sql.Scan() strfmt.MySQLDatetime from: %#v", v) 45 } 46 return nil 47 } 48 49 func (dt MySQLDatetime) Value() (driver.Value, error) { 50 return time.Unix(dt.Unix(), 0), nil 51 } 52 53 func (dt MySQLDatetime) String() string { 54 return time.Time(dt).In(CST).Format(time.RFC3339) 55 } 56 57 func (dt MySQLDatetime) Format(layout string) string { 58 return time.Time(dt).In(CST).Format(layout) 59 } 60 61 var _ interface { 62 encoding.TextMarshaler 63 encoding.TextUnmarshaler 64 } = (*MySQLDatetime)(nil) 65 66 func (dt MySQLDatetime) MarshalText() ([]byte, error) { 67 if dt.IsZero() { 68 return []byte(""), nil 69 } 70 str := dt.String() 71 return []byte(str), nil 72 } 73 74 func (dt *MySQLDatetime) UnmarshalText(data []byte) (err error) { 75 str := string(data) 76 if len(str) == 0 || str == "0" { 77 str = MySQLDatetimeZero.String() 78 } 79 *dt, err = ParseMySQLDatetimeFromString(str) 80 return 81 } 82 83 func (dt MySQLDatetime) Unix() int64 { 84 return time.Time(dt).Unix() 85 } 86 87 func (dt MySQLDatetime) IsZero() bool { 88 unix := dt.Unix() 89 return unix == 0 || unix == MySQLDatetimeZero.Unix() 90 } 91 92 func (dt MySQLDatetime) In(loc *time.Location) MySQLDatetime { 93 return MySQLDatetime(time.Time(dt).In(loc)) 94 } 95 96 // 获取当天最后一秒(东8区) 97 func (dt MySQLDatetime) GetTodayLastSecCST() MySQLDatetime { 98 return MySQLDatetime(GetTodayLastSecInLocation(time.Time(dt), CST)) 99 } 100 101 // 添加N个工作日(东8区) 102 func (dt MySQLDatetime) AddWorkingDaysCST(days int) MySQLDatetime { 103 return MySQLDatetime(AddWorkingDaysInLocation(time.Time(dt), days, CST)) 104 } 105 106 // 获取当天0点(东8区) 107 func (dt MySQLDatetime) GetTodayFirstSecCST() MySQLDatetime { 108 return MySQLDatetime(GetTodayFirstSecInLocation(time.Time(dt), CST)) 109 }