I have a Go string x := "2020-09-01T21:46:43Z"
Here is my Protobuf3:
message MyMessage {
google.protobuf.Timestamp mytimestamp = 1;
}
How can I convert this string x
to a google.protobuf.Timestamp
?
Use the ptypes package which has helpers to convert to/from protobuf types.
Two functions to help you are:
ptypes.Timestamp: Converts a Timestamp
to a time.Time
:
func Timestamp(ts *timestamppb.Timestamp) (time.Time, error)
Call the timestamppb.New function. This converts a time.Time
to a Timestamp
:
func timestamppb.New(t time.Time) *timestamppb.Timestamp
Note that both deal with a time.Time, the time type in the standard library. You will first need to parse your string into a time.Time
using time.Parse.
Putting it all together we have:
package main
import (
"fmt"
"time"
"google.golang.org/protobuf/types/known/timestamppb"
)
func main() {
t, err := time.Parse(time.RFC3339, "2020-09-01T21:46:43Z")
if err != nil {
panic(err)
}
pb := timestamppb.New(t)
fmt.Println(pb)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With