1

I'm working on a middleware using golang. I'm consuming a REST-API which returns a Date in form of a LocalDateTime (e.g. "created": "2022-01-09T00:00:00",) and it should get mapped into an protoc message with the data class google/protobuf/timestamp.proto as we don't want to do the converting in the frontend. But apparently the timestamp.proto only supports DateTime with a timezone (so like that "created": "2022-01-09T00:00:00Z...") but as its an external API I'm consuming I cant change their datatype to DateTime. Does anyone know how to find and elegant solution without doing the complete mapping/unmashalling process manually?

That's the protoc message: google.protobuf.Timestamp created = 7 [json_name = "created"];

That's the unmashaller we're using: err = protojson.Unmarshal(body, protoMessageClass)

That's the error I'm getting: ERROR: proto: (line ...): invalid google.protobuf.Timestamp value "2021-12-07T00:00:00""

jemai
  • 11
  • 1
  • 1
    Parse your LocalDateTime `2022-01-09T00:00:00` to this format `2022-01-09T00:00:00Z...` . Then do the mapping it will work. Refer this : https://stackoverflow.com/questions/57342875/parsing-datetimestamps-with-timezone-offset-in-go-using-google-protobuf-timestam – Ashutosh Singh Jan 11 '22 at 13:38

1 Answers1

0

First convert the time you receive as a string to a time.Time object:

t, err := time.Parse("2006-01-02T15:04:05", val)

Here "2006-01-02T15:04:05" represents the layout you expect.

Then you can use timestamppb built-in function to create a protobuf timestamp from a time.Time object:

tpb := timestamppb.New(t)

If you need the opposite, you can use AsTime from timestampb.Timestamp type and then format from time.Time object to make a string.

Benjamin Barrois
  • 2,566
  • 13
  • 30