登录
首页 >  Golang >  Go问答

如何在我的时区下使用 Timestamp Protobuff 替代 github 版本的时间戳?

来源:stackoverflow

时间:2024-02-26 08:45:24 238浏览 收藏

大家好,我们又见面了啊~本文《如何在我的时区下使用 Timestamp Protobuff 替代 github 版本的时间戳?》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

好吧,当我使用以下方法生成新的 protobuff 文件时,我刚刚意识到一些事情:

protoc my_file.proto --go_out=./

我的 .proto 结构看起来像:

message myrequest {
 google.protobuf.timestamp my_time = 1;
}

如果我在 2021 年左右使用 protoc 命令,我会得到:

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

type myrequest struct {
    mytime *timestamp.timestamp `protobuf:"bytes,1,opt,name=my_time,json=mytime,proto3" json:"my_time,omitempty"`
}

但现在我会得到:

import timestamppb "google.golang.org/protobuf/types/known/timestamppb"
    
type MyRequest struct {
    MyTime *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=my_time,json=myTime,proto3" json:"my_time,omitempty"`
}

主要问题是旧结构在我的时区中显示mytime,但新结构将其转换为 utc+0。有谁知道如何解决这个问题吗?


正确答案


可以看到this方法是调用.utc()方法。

从该方法来看,您可以创建自定义函数来返回您所在时区的时间。

这是示例:

func ForMyTimeZone(x *timestamppb.Timestamp) time.Time {
    return time.Unix(int64(x.GetSeconds()), int64(x.GetNanos()))
}

终于介绍完啦!小伙伴们,这篇关于《如何在我的时区下使用 Timestamp Protobuff 替代 github 版本的时间戳?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>