Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to google.protobuf.Timestamp?

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?

like image 210
Saqib Ali Avatar asked Oct 17 '25 14:10

Saqib Ali


1 Answers

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)
}
like image 152
Marc Avatar answered Oct 20 '25 05:10

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!