How can I test google.protobuf.Timestamp in Javascript?

Yaelz picture Yaelz · Feb 24, 2019 · Viewed 8.8k times · Source

Using a proto file from an API created in Scala. My code is in JS, trying to test my code and getting the following error:

AssertionError [ERR_ASSERTION]: invalid return value: post[0].lastPublishedDate: Date expected

Tried and didn't work:

  1. lastPublishedDate: {seconds: <date>, nano: <date>}, with date being a date's toISOString() like mentioned in the docs (https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/timestamp.proto#L115)
  2. lastPublishedDate: new Date().toISOString()
  3. Just putting 2019-02-18T14:18:45.346Z (that's what the API seems to return when I call it) as the date.

Nothing seems to work for me.

The only other reference to this I could find online is this: https://github.com/dcodeIO/protobuf.js/issues/437 and it also seems unsolved.

Has anyone managed to work with google.protobuf.Timestamp in JS?

Answer

Mohammad Hajiaghazadeh picture Mohammad Hajiaghazadeh · Oct 15, 2019

you can use this function to generate Date based on this google/protobuf/timestamp.proto

const getDate = ()=>{
    if (window.proto) {
        const proto = window.proto;
        const timeMS = Date.now();
        const timestamp = new proto.google.protobuf.Timestamp()
        timestamp.setSeconds(timeMS / 1000);
        timestamp.setNanos((timeMS % 1000) * 1e6);
        return timestamp;
    }
}

OR you can use this one as well:

const date = new proto.google.protobuf.Timestamp()
date.fromDate(new Date())

and for getting JS date you can use toDate() method from proto.google.protobuf.Timestamp

hope it helps you.