【问题标题】:How to save a date value in firestore如何在firestore中保存日期值
【发布时间】:2018-07-23 06:40:10
【问题描述】:

type="date" 在 html 中保存为 firestore 中的字符串。

在 html 文件中。

<input #scheduledStartDate="ngModel" [(ngModel)]="reposition.scheduledStartDate"
name="scheduledStartDate" id="scheduledStartDate" class="input is-normal"
type="date" required placeholder="Leaving...">

来自接口 .ts 文件

scheduledStartDate?: DateTimeFormat;

也试过了

scheduledStartDate?: Date;

同样的结果。

这两个选项都将输入的日期值保存为 Firestore 中的字符串,例如“2018-01-02”而不是时间戳。

【问题讨论】:

  • 你能提供一些示例代码吗?
  • 你找到方法了吗?
  • 如果您使用 Firestore 控制台创建文档并选择 timestamp 作为字段类型,它将保存为 ISO8601 字符串。此外,文档的createTimeupdateTime 参数也以这种格式存储。因此,除非您有非常具体的要求将该日期存储为 Linux/Unix 时间戳,否则我建议您坚持使用当前格式。

标签: angular google-cloud-firestore


【解决方案1】:

在将 javascript 对象保存到 firestore 之前,只需创建一个 Date() 实例并像这样传递值 new Date("December 10, 1815")

语法

var docData = {
    stringExample: "Hello world!",
    booleanExample: true,
    numberExample: 3.14159265,
    dateExample: new Date("December 10, 1815"),
    arrayExample: [5, true, "hello"],
    nullExample: null,
    objectExample: {
        a: 5,
        b: {
            nested: "foo"
        }
    }
};
db.collection("data").doc("one").set(docData).then(function() {
    console.log("Document successfully written!");
})

Cloud Firestore 支持,

日期和时间 - 时间顺序 - 当存储在 Cloud Firestore 中时,精确到微秒;任何额外的精度都会向下舍入。

注意

当查询涉及具有混合类型值的字段时,Cloud Firestore 使用基于内部表示的确定性排序。

官方链接

https://firebase.google.com/docs/firestore/manage-data/data-types https://firebase.google.com/docs/firestore/manage-data/add-data

【讨论】:

    【解决方案2】:

    你应该使用下面的firestore函数firebase.firestore.Timestamp.fromDate

    const mydoc = {
      name: 'John Doe',
      createdAt: firebase.firestore.Timestamp.fromDate(new Date("December 10, 1815")) 
    }
    
    // save the document 
    db.collection("mycollection").doc("id1").set(mydoc).then(function() {
        console.log("Document successfully written!");
    });
    

    【讨论】:

      猜你喜欢
      • 2018-12-18
      • 2021-03-04
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多