tonytonytony的gravatar头像
tonytonytony 2021-07-10 14:12:17

go格式化日期

项目描述

go 格式日期算法

运行环境

goland

项目技术(必填)

golang

是否原创(转载必填原文地址)

原创

项目截图(必填)

go格式化日期

运行截图(必填)

go格式化日期

代码片段

package main

import (
   "encoding/json"
   "fmt"
   "time"
)

type Time time.Time

const (
   timeFormart = "2006-01-02 15:04:05"
)

func (t *Time) UnmarshalJSON(data []byte) (err error) {
   now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.Local)
   *t = Time(now)
   return
}

func (t Time) MarshalJSON() ([]byte, error) {
   b := make([]byte, 0, len(timeFormart)+2)
   b = append(b, '"')
   b = time.Time(t).AppendFormat(b, timeFormart)
   b = append(b, '"')
   return b, nil
}

func (t Time) String() string {
   return time.Time(t).Format(timeFormart)
}

type Person struct {
   Id       int64  `json:"id"`
   Name     string `json:"name"`
   Birthday Time   `json:"birthday"`
}

func TestTimeJson() {
   now := Time(time.Now())
   fmt.Println(now)
   src := `{"id":5,"name":"xiaoming","birthday":"2016-06-30 16:09:51"}`
   p := new(Person)
   err := json.Unmarshal([]byte(src), p)
   if err != nil {
      fmt.Println(err)
   }
   fmt.Println(p)
   fmt.Println(time.Time(p.Birthday))
   js, _ := json.Marshal(p)
   fmt.Println(string(js))
}





func main()  {
   TestTimeJson()
}

打赏

最代码最近下载分享源代码列表最近下载
最代码最近浏览分享源代码列表最近浏览
2206371875  LV7 2023年12月5日
只要有你  LV8 2021年12月3日
1515997875 2021年9月26日
暂无贡献等级
CrystalQ  LV8 2021年8月22日
最代码_码鑫源  LV6 2021年7月30日
terryang  LV19 2021年7月20日
bk468822 2021年7月17日
暂无贡献等级
interface  LV22 2021年7月15日
情绪吖  LV3 2021年7月13日
212828939  LV16 2021年7月12日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友