35 Star 427 Fork 70

GVPdromara/carbon

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
type_format.go 2.23 KB
一键复制 编辑 原始数据 按行查看 历史
kuafuRace 提交于 2天前 . v2.6.6
package carbon
import (
"bytes"
"database/sql/driver"
)
// FormatTyper defines a FormatTyper interface.
type FormatTyper interface {
~string
Format() string
}
// FormatType defines a FormatType generic struct.
type FormatType[T FormatTyper] struct {
*Carbon
}
// NewFormatType returns a new FormatType generic instance.
func NewFormatType[T FormatTyper](c *Carbon) *FormatType[T] {
return &FormatType[T]{
Carbon: c,
}
}
// Scan implements driver.Scanner interface for FormatType generic struct.
func (t *FormatType[T]) Scan(src any) error {
var c *Carbon
switch v := src.(type) {
case nil:
return nil
case []byte:
c = Parse(string(v), DefaultTimezone)
case string:
c = Parse(v, DefaultTimezone)
case int64:
c = CreateFromTimestamp(v, DefaultTimezone)
case StdTime:
c = CreateFromStdTime(v, DefaultTimezone)
case *StdTime:
c = CreateFromStdTime(*v, DefaultTimezone)
default:
return ErrFailedScan(v)
}
*t = *NewFormatType[T](c)
return t.Error
}
// Value implements driver.Valuer interface for FormatType generic struct.
func (t FormatType[T]) Value() (driver.Value, error) {
if t.IsNil() || t.IsZero() || t.IsEmpty() {
return nil, nil
}
if t.HasError() {
return nil, t.Error
}
return t.StdTime(), nil
}
// MarshalJSON implements json.Marshal interface for FormatType generic struct.
func (t FormatType[T]) MarshalJSON() ([]byte, error) {
if t.IsNil() || t.IsZero() || t.IsEmpty() {
return []byte(`null`), nil
}
if t.HasError() {
return []byte(`null`), t.Error
}
v := t.Format(t.getFormat())
b := make([]byte, 0, len(v)+2)
b = append(b, '"')
b = append(b, v...)
b = append(b, '"')
return b, nil
}
// UnmarshalJSON implements json.Unmarshal interface for FormatType generic struct.
func (t *FormatType[T]) UnmarshalJSON(src []byte) error {
v := string(bytes.Trim(src, `"`))
if v == "" || v == "null" {
return nil
}
*t = *NewFormatType[T](ParseByFormat(v, t.getFormat()))
return t.Error
}
// String implements Stringer interface for FormatType generic struct.
func (t *FormatType[T]) String() string {
if t == nil || t.IsInvalid() || t.IsZero() {
return ""
}
return t.Format(t.getFormat())
}
// getFormat returns the set format.
func (t *FormatType[T]) getFormat() string {
var typer T
return typer.Format()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dromara/carbon.git
git@gitee.com:dromara/carbon.git
dromara
carbon
carbon
master

搜索帮助