Protobuf 中的 timestamp 與 Go time 的轉換

在使用 GRPC 時,經常用到時間,如何將 protobuf 中的 timestamp 與 go 中的 time 進行轉換,直接影響平時開發的效率

通過查看 protobuf 源碼包中的方法,找到兩組方法用於 protobuf 中的 timestamp 與 go 中的 time 進行相互轉換

package main

import (
	"fmt"
	"time"

	"github.com/golang/protobuf/ptypes"
	"github.com/golang/protobuf/ptypes/timestamp"
)


func main()  {
	var timeProto *timestamp.Timestamp
	var timeGo time.Time

	timeProto = ptypes.TimestampNow()
	fmt.Println(timeProto) // seconds:1587894893  nanos:853238000
	timeGo = time.Now()
	fmt.Println(timeGo) // 2020-04-26 17:54:53.853474 +0800 CST m=+0.000831812

	timeGo, err := ptypes.Timestamp(timeProto)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(timeGo) // 2020-04-26 09:54:53.853238 +0000 UTC

	timeProto, err = ptypes.TimestampProto(timeGo)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(timeProto) // seconds:1587894893  nanos:853238000

	str := ptypes.TimestampString(timeProto)
	fmt.Println(str) // 2020-04-26T09:54:53.853238Z
}

詳細解讀請點擊連接查看
【源碼閱讀】 protobuf 中的 timestamp 包

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章