首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何获取firestore时间戳

如何获取firestore时间戳
EN

Stack Overflow用户
提问于 2018-04-25 08:29:56
回答 4查看 55.7K关注 0票数 14

我试图获取我在firestore中创建的文档的时间戳,但我得到的是:

myService.ts

代码语言:javascript
复制
getDomiciliarios() {
this.domiciliarios = this.afs.collection('domiciliarios').snapshotChanges().map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data() as Domiciliario;
    const id = a.payload.doc.id;
    const date = firebase.firestore.FieldValue.serverTimestamp();
    return { id, ...data, date };
  });
});

return this.domiciliarios;
}

myComponent.ts

代码语言:javascript
复制
ngOnInit() {
const domiciliarios = this.fs.getDomiciliarios()
  .subscribe(data => this.dataSource.data = data, date => date);
}

myComponent.html

代码语言:javascript
复制
<ng-container matColumnDef="fecha">
  <mat-header-cell *matHeaderCellDef mat-sort-header> Fecha </mat-header-cell>
  <mat-cell *matCellDef="let domiciliario"> {{ domiciliario.date }} </mat-cell>
</ng-container>

我该如何打印时间戳,我应该事先创建它吗?

EN

回答 4

Stack Overflow用户

发布于 2018-06-18 07:06:03

如果需要firebase.firestore.FieldValue.serverTimestamp()的日期值,可以使用.toDate()。参见FireStore Timesteamp。在您的示例中,它将是模板中的domiciliario.date.toDate()

票数 18
EN

Stack Overflow用户

发布于 2018-04-25 13:44:57

我认为您使用FieldValue.serverTimestamp()的方式是错误的:正如文档所述,firebase.firestore.FieldValue方法返回“在使用set()或()编写文档字段时可以使用的值”。(参见https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue)

在读取数据时使用的是serverTimestamp()方法。

正如您在问题末尾提到的,您应该在创建数据库中的记录时使用它。

编辑:如下所示:

代码语言:javascript
复制
const timestamp = firebase.firestore.FieldValue.serverTimestamp();
docRef.update({ updatedAt: timestamp });

然后,您可以像这样查询

代码语言:javascript
复制
collectionRef.orderBy('updatedAt').get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            ...
        });
    })
    .catch(err => {
        console.log('Error getting documents', err);
    });

上面的代码是纯JavaScript的,你可以把它改编成angular和type脚本,但原理是一样的。

票数 14
EN

Stack Overflow用户

发布于 2019-10-24 19:58:17

如果想要将当前日期作为时间戳,可以使用以下命令

用于Firebase函数的

代码语言:javascript
复制
import admin = require('firebase-admin');

const todayAsTimestamp = admin.firestore.Timestamp.now()

用于本地项目的

代码语言:javascript
复制
import { Timestamp } from '@google-cloud/firestore';

const myTimestampAsDate = Timestamp.now()
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50012438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档