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
}
原创文章 44 获赞 15 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_32828933/article/details/105772122
今日推荐