简体   繁体   English

如何在 Firebase 云函数中添加时间戳

[英]How to add Timestamp in firebase cloud functions

I am trying to add Timestamp in Firestore document on Firebase Cloud functions.我正在尝试在 Firebase Cloud 函数的 Firestore 文档中添加Timestamp

I had tried firestore.Timestamp.fromDate(new Date()) , but its not working.我试过firestore.Timestamp.fromDate(new Date()) ,但它不起作用。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const firestore = admin.firestore();
const createdAt = firestore.Timestamp.fromDate(new Date());
console.log(createdAt);

Value of createdAt should return the server timestamp, but its throwing error. createdAt值应该返回服务器时间戳,但它的抛出错误。

Instead of this:取而代之的是:

const firestore = admin.firestore();
const createdAt = firestore.Timestamp.fromDate(new Date());

Try this:试试这个:

const firestore = admin.firestore;
const createdAt = firestore.Timestamp.fromDate(new Date());

Might be hard to spot the difference.可能很难发现差异。 So here is the explanation: You are calling the function "firestore()" of the object "admin" instead of accessing the property "firestore" of the object "admin" which has the property "Timestamp" you are looking for.所以这里是解释:您正在调用对象“admin”的函数“firestore()”,而不是访问具有您正在查找的属性“Timestamp”的对象“admin”的属性“firestore”。

This line of code has a syntax error in it.这行代码有语法错误。 It's not valid JavaScript:这不是有效的 JavaScript:

const createdAt: firestore.Timestamp.fromDate(new Date());

It looks like you meant to write this:看起来你打算写这个:

const createdAt = firestore.Timestamp.fromDate(new Date());

I personallly used const timestamp = new Date().getTime();我个人使用const timestamp = new Date().getTime(); then saved it to the firstore document and it worked.然后将其保存到 firstore 文档并且它起作用了。

当专门使用云函数钩子functions.auth.user().onCreate((user) => {})我使用user.metadata.creationTime来获得确切的创建时间,而不必进入时区和日期/时间问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM