Golang: How to Convert time.Time to a Protobuf Timestamp?
Asked Answered
I

4

18

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?

Indohittite answered 3/11, 2021 at 2:11 Comment(1)
Recommend using 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
L
29

See New and Timestamp.AsTime in timestamppb

These support conversion to/from time.Time and Timestamp

Lashing answered 3/11, 2021 at 2:26 Comment(0)
M
3

Try using the timestamppb.New

like this:

newTimeStamp:=timestamppb.New(your_time)
Morrismorrison answered 7/5, 2024 at 9:28 Comment(0)
W
0

Instead of using like this

timeNow := time.Now()
timestamp := timestamppb.Timestamp{
    Seconds: timeNow.Unix(),
    Nanos:   int32(timeNow.Nanosecond()),
} 

try this :

timestamppb.New(time.Now())
Wingding answered 7/5, 2024 at 8:31 Comment(0)
E
-4

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
Eraeradiate answered 26/8, 2022 at 13:16 Comment(2)
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.