6

使用 Scala 创建的 API 中的 proto 文件。我的代码在 JS 中,试图测试我的代码并得到以下错误:

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

试过但没有用:

  1. lastPublishedDate: {seconds: <date>, nano: <date>},日期是文档中提到的日期 toISOString() ( https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/timestamp.proto#L115 )
  2. lastPublishedDate: new Date().toISOString()
  3. 只需将2019-02-18T14:18:45.346Z(这就是我调用它时 API 似乎返回的内容)作为日期。

似乎没有什么对我有用。

我可以在网上找到的唯一其他参考是: https ://github.com/dcodeIO/protobuf.js/issues/437 ,它似乎也没有解决。

有没有人设法在 JS 中使用 google.protobuf.Timestamp ?

4

2 回答 2

12

您可以使用此函数根据此生成日期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;
    }
}

或者你也可以使用这个:

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

为了获取 JS 日期,您可以使用toDate()方法 fromproto.google.protobuf.Timestamp

希望它可以帮助你。

于 2019-10-15T09:36:26.693 回答
1

所以显然这是一个常规的 JS 日期(new Date()),就像可以从错误消息中找出的那样......

于 2019-02-24T11:52:29.240 回答