没有合适的资源?快使用搜索试试~ 我知道了~
首页【源码阅读】 protobuf 中的 timestamp 包
文章目录Timestamptimestamp.go如何使用 Timestamp path: google/protobuf/timestamp.proto 在 timestamppb 中 Timestamp 包含两个字段 seconds 表示秒 nanos 表示纳秒 message Timestamp { int64 seconds = 1; int32 nanos = 2; } timestamp.go path: github.com/golang/protobuf/ptypes/timestamp.go package ptypes import ( errors fm
资源详情
资源评论
资源推荐

【源码阅读】【源码阅读】 protobuf 中的中的 timestamp 包包
文章目录文章目录Timestamptimestamp.go如何使用
Timestamp
path: google/protobuf/timestamp.proto
在 timestamppb 中 Timestamp 包含两个字段
seconds 表示秒
nanos 表示纳秒
message Timestamp {
int64 seconds = 1;
int32 nanos = 2;
}
timestamp.go
path: github.com/golang/protobuf/ptypes/timestamp.go
package ptypes
import (
"errors"
"fmt"
"time"
timestamppb "github.com/golang/protobuf/ptypes/timestamp"
)
const (
// 定义了当前包内方法所支持的最大时间戳和最小时间戳
// 最小时间开始于 1 年 1 月 1 日 0:0:0 0
minValidSeconds = -62135596800
// 最大时间结束于 10000 年 1 月 1 日 0:0:0 0
maxValidSeconds = 253402300800
)
// Timestamp 方法将 *timestamppb.Timestamp 类型转换为 time.Time 类型
// 如果参数值为 nil,则返回 time.Unix(0, 0).UTC()
func Timestamp(ts *timestamppb.Timestamp) (time.Time, error) {
var t time.Time
if ts == nil {
t = time.Unix(0, 0).UTC()
} else {
t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
}
return t, validateTimestamp(ts)
}
// TimestampNow 方法返回一个当前时间的 timestamppb.Timestamp
func TimestampNow() *timestamppb.Timestamp {
ts, err := TimestampProto(time.Now())
if err != nil {
panic("ptypes: time.Now() out of Timestamp range")
}
return ts
}
// TimestampProto 方法将 time.Time 类型转换为 *timestamppb.Timestamp 类型
func TimestampProto(t time.Time) (*timestamppb.Timestamp, error) {
ts := ×tamppb.Timestamp{
Seconds: t.Unix(),
Nanos: int32(t.Nanosecond()),
}
if err := validateTimestamp(ts); err != nil {
return nil, err
}
return ts, nil
}



















安全验证
文档复制为VIP权益,开通VIP直接复制

评论0