我正在解码来自 JSON API 的 GET 请求。其中一些字段是 Unix 时间戳(以毫秒为单位)。对于这些字段,我编写了一个处理解码的方法。为此,我需要创建一个新的本地类型 Datetime
.
type Datetime time.Time
type Response struct {
Status string `json:"status"`
CreatedAt Datetime `json:"created_at"`
}
// Handles unmarshalling of Time from the API
func (dt *Datetime) UnmarshalJSON(b []byte) error {
var unixTimeMs int64
if err := json.Unmarshal(b, &unixTimeMs); err != nil {
return err
}
*dt = Datetime(time.Unix(0, unixTimeMs*1000000))
return nil
}
现在我有了这个新的 Response 对象,我想调用
time.Time
日期时间的方法。我尝试过转换对象(即 response.CreatedAt.(time.Time)),但这会导致 panic 。如何调用
time.Time#string
之类的方法在 Datetime
?
最佳答案
Convert日期时间为 time.Time
调用Time
方法。例子:
fmt.Println(time.Time(dt).String())
另一种方法是使用带有嵌入时间字段的结构:
type Datetime struct {
time.Time
}
全部
time.Time
方法升级为 Datetime
类型。修改UnmarshalJSON方法设置dt.Time
而不是 *dt
.
关于go - 访问类型声明父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61718253/