carbon/encoding.go

43 lines
1017 B
Go
Raw Normal View History

2021-07-03 15:31:42 +08:00
package carbon
import (
2021-07-19 09:53:30 +08:00
"bytes"
2021-07-03 15:31:42 +08:00
"fmt"
)
2023-12-22 16:09:01 +08:00
// MarshalJSON implements the interface Marshaler for Carbon struct.
// 实现 Marshaler 接口
func (c Carbon) MarshalJSON() ([]byte, error) {
if c.Error != nil {
return nil, c.Error
}
2023-12-26 21:49:48 +08:00
key, value, tz := c.parseTag()
data := fmt.Sprintf(`"%s"`, c.ToDateTimeString(tz))
2023-12-22 16:09:01 +08:00
if key == "layout" {
2023-12-26 21:49:48 +08:00
data = fmt.Sprintf(`"%s"`, c.Layout(value, tz))
}
2023-12-22 16:09:01 +08:00
if key == "format" {
2023-12-26 21:49:48 +08:00
data = fmt.Sprintf(`"%s"`, c.Format(value, tz))
}
2023-12-26 21:49:48 +08:00
return []byte(data), nil
}
2023-12-22 16:09:01 +08:00
// UnmarshalJSON implements the interface Unmarshaler for Carbon struct.
// 实现 Unmarshaler 接口
func (c *Carbon) UnmarshalJSON(b []byte) error {
if c.Error != nil {
return c.Error
}
2023-12-26 21:49:48 +08:00
key, value, tz := c.parseTag()
data := fmt.Sprintf("%s", bytes.Trim(b, `"`))
2023-12-22 16:09:01 +08:00
if key == "layout" {
2023-12-26 21:49:48 +08:00
*c = ParseByLayout(data, value, tz)
c.tag = fmt.Sprintf("layout:%s;tz:%s", value, tz)
}
2023-12-22 16:09:01 +08:00
if key == "format" {
2023-12-26 21:49:48 +08:00
*c = ParseByFormat(data, value, tz)
c.tag = fmt.Sprintf("format:%s;tz:%s", value, tz)
}
2022-11-04 10:47:29 +08:00
return c.Error
}