I have a time.Time variable in Golang 10-30 00:49:07.1236
that needs to be converted to a Go Protobuf timestamp.Timestamp. Any idea on what functions can be used to accomplish this? Or am I looking at this from the wrong angle?
Golang: How to Convert time.Time to a Protobuf Timestamp?
Asked Answered
See New
and Timestamp.AsTime
in timestamppb
These support conversion to/from time.Time
and Timestamp
Try using the timestamppb.New
like this:
newTimeStamp:=timestamppb.New(your_time)
Instead of using like this
timeNow := time.Now()
timestamp := timestamppb.Timestamp{
Seconds: timeNow.Unix(),
Nanos: int32(timeNow.Nanosecond()),
}
try this :
timestamppb.New(time.Now())
Below code will give convert time.Time to protobuf timestamppb format
import "google.golang.org/protobuf/types/known/timestamppb"
timeNow := time.Now()
timestamp := timestamppb.Timestamp{
Seconds: timeNow.Unix(),
Nanos: int32(timeNow.Nanosecond()),
}
fmt.Printf("as timestamp %+v\n", timestamp)
fmt.Printf("as time.Time %+v\n", timestamp.AsTime().Local())
Output looks like this:
as timestamp {state:{NoUnkeyedLiterals:{} DoNotCompare:[] DoNotCopy:[] atomicMessageInfo:<nil>} sizeCache:0 unknownFields:[] Seconds:1694773177 Nanos:777135000}
as time.Time 2023-09-15 15:49:37.777135 +0530 IST
Question: Convert given timestamp to time and vice versa. Not finding current time. –
Curch
Use
timestampb.New(time.Now())
, as per the top answer. –
Stole © 2022 - 2025 — McMap. All rights reserved.
godoc
or going to pkg.go.dev to read the documentation for the libraries you are using. For example, go to pkg.go.dev/google.golang.org/protobuf/types/known/… – Proliferous