github.com/kunlun-qilian/sqlx/v3@v3.0.0/datatypes/datetime.go (about)

     1  package datatypes
     2  
     3  import (
     4  	"database/sql"
     5  	"database/sql/driver"
     6  	"encoding"
     7  	"fmt"
     8  	"time"
     9  )
    10  
    11  var (
    12  	DatetimeZero = Datetime(time.Time{})
    13  )
    14  
    15  type MySQLDatetime = Datetime
    16  
    17  // openapi:strfmt date-time
    18  type Datetime time.Time
    19  
    20  func (Datetime) DataType(e string) string {
    21  	return "timestamp"
    22  }
    23  
    24  func ParseDatetimeFromString(s string) (dt Datetime, err error) {
    25  	var t time.Time
    26  	t, err = time.Parse(time.RFC3339, s)
    27  	dt = Datetime(t)
    28  	return
    29  }
    30  
    31  func ParseDatetimeFromStringWithFormatterInCST(s, formatter string) (dt Datetime, err error) {
    32  	var t time.Time
    33  	t, err = time.ParseInLocation(formatter, s, CST)
    34  	dt = Datetime(t)
    35  	return
    36  }
    37  
    38  var _ interface {
    39  	sql.Scanner
    40  	driver.Valuer
    41  } = (*Datetime)(nil)
    42  
    43  func (dt *Datetime) Scan(value interface{}) error {
    44  	switch v := value.(type) {
    45  	case time.Time:
    46  		*dt = Datetime(time.Unix(v.Unix(), 0))
    47  	case nil:
    48  		*dt = DatetimeZero
    49  	default:
    50  		return fmt.Errorf("cannot sql.Scan() strfmt.Datetime from: %#v", v)
    51  	}
    52  	return nil
    53  }
    54  
    55  func (dt Datetime) Value() (driver.Value, error) {
    56  	return time.Unix(dt.Unix(), 0), nil
    57  }
    58  
    59  func (dt Datetime) String() string {
    60  	if dt.IsZero() {
    61  		return ""
    62  	}
    63  	return time.Time(dt).In(CST).Format(time.RFC3339)
    64  }
    65  
    66  func (dt Datetime) Format(layout string) string {
    67  	return time.Time(dt).In(CST).Format(layout)
    68  }
    69  
    70  var _ interface {
    71  	encoding.TextMarshaler
    72  	encoding.TextUnmarshaler
    73  } = (*Datetime)(nil)
    74  
    75  func (dt Datetime) MarshalText() ([]byte, error) {
    76  	return []byte(dt.String()), nil
    77  }
    78  
    79  func (dt *Datetime) UnmarshalText(data []byte) (err error) {
    80  	str := string(data)
    81  	if len(str) == 0 || str == "0" {
    82  		return nil
    83  	}
    84  	*dt, err = ParseDatetimeFromString(str)
    85  	return
    86  }
    87  
    88  func (dt Datetime) Unix() int64 {
    89  	return time.Time(dt).Unix()
    90  }
    91  
    92  func (dt Datetime) IsZero() bool {
    93  	unix := dt.Unix()
    94  	return unix == 0 || unix == DatetimeZero.Unix()
    95  }
    96  
    97  func (dt Datetime) In(loc *time.Location) Datetime {
    98  	return Datetime(time.Time(dt).In(loc))
    99  }