How can I test google.protobuf.Timestamp in Javascript?
Asked Answered
S

2

9

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?

Sangsanger answered 24/2, 2019 at 7:46 Comment(0)
M
15

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.

Murat answered 15/10, 2019 at 9:36 Comment(3)
setSeconds and setNanos didn't work for me for some reason, but the fromDate did. Thanks!Underquote
Same with me and this answer saved my day. Huge thank you!Rathskeller
Thank you - wow this is janky syntax. WTF google!??!Metamorphose
S
2

So apparently it was a regular JS date (new Date()), like could be figured out from the error message...

Sangsanger answered 24/2, 2019 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.