欢迎,来自IP地址为:18.191.147.190 的朋友


Go 语言可以轻松实现日期时间间的转换,对于处理 Unix 时间戳也不在话下。Unix 时间戳,指的是自 UTC 时间1970年1月1日零时至当前所有的秒数。

以下代码可以实现将 Unix 时间戳转换为 date 字符串:

package main

import (
	"time"
	"fmt"
)

func main() {
	var unixTime int64 = time.Now().Unix()
	fmt.Println(unixTime)
	t := time.Unix(unixTime, 0)
	strDate := t.Format(time.UnixDate)
	fmt.Println(strDate)
}

编译执行后,会得到当前的时间戳和当时时间字符串,示例输出如下:

1573611958
Wed Nov 13 10:25:58 CST 2019

现在,我们编写一个较为复杂的程序。首先创建一个结构”Epoch”,并且绑定两个方法,其中”MarshalJSON”方法用于将时间戳转换为 date 字符串;而”UnmarshalJSON”方法会将 date 字符串转换为时间戳。两个方法会在我们进行 JSON 编解码时被调用。

package main

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

type Epoch int64

func (t Epoch) MarshalJSON() ([]byte, error) {
	strDate := time.Time(time.Unix(int64(t), 0)).Format(time.RFC3339)
	out := []byte(`"` + strDate + `"`)
	return out, nil
}

func (t *Epoch) UnmarshalJSON(b []byte) (err error) {
	s := strings.Trim(string(b), "\"")
	q, err := time.Parse(time.RFC3339, s)
	if err != nil {
		return err
	}
	*t = Epoch(q.Unix())
	return nil
}

type MyStruct struct {
	Date Epoch
}

func main() {
	s := MyStruct{Date: Epoch(201911130000)}
	fmt.Println(s.Date)
	js, err := json.Marshal(s)
	fmt.Println(string(js), err)

	b := []byte(`{"date": "2019-11-13T12:00:00Z"}`)
	var m MyStruct
	err = json.Unmarshal(b, &m)
	fmt.Println(m.Date, err)
}

输出结果如下:

201911130000
{"Date":"8368-04-23T17:00:00+08:00"} 
1573646400 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注