golang时间从数据库读取时间

来源:互联网 发布:北京金山软件大厦 编辑:程序博客网 时间:2024/06/05 21:51

golang从数据库读取时间,如果遇到时间为Null,那么可以采用类似NullInt64的方法!

package mainimport ("database/sql/driver""encoding/json""fmt""time")type NullTime struct {Time  time.TimeValid bool // 是否有值}//实现它的赋值方法(注意,这个方属于指针)func (nt *NullTime) Scan(value interface{}) error {nt.Time, nt.Valid = value.(time.Time)return nil}//实现它的取值方式func (nt NullTime) Value() (driver.Value, error) {if !nt.Valid {return nil, nil}return nt.Time, nil}func (this NullTime) MarshalJSON() ([]byte, error) {if this.Valid {var stamp = fmt.Sprintf("\"%s\"", time.Time(this.Time).Format("2006-01-02 15:04:05"))return []byte(stamp), nil} else {return nil, nil}}func main() {var t NullTimet.Scan(nil)body, _ := json.Marshal(t)fmt.Printf("%s", string(body))t.Scan(time.Now())body, _ = json.Marshal(t)fmt.Printf("%s", string(body))}


0 0