node.js 如何在 Cloud Functions for Firebase 中获取服务器时间戳?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43567312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:10:57  来源:igfitidea点击:

How do I get the server timestamp in Cloud Functions for Firebase?

node.jsfirebasefirebase-realtime-databasegoogle-cloud-functionsfirebase-admin

提问by Justin Handley

I know you can pull the server timestamp in web, ios, and android - but what about the new Cloud Functions for Firebase? I can't figure out how to get the server timestamp there? Use case is me wanting to timestamp an email when it arrives.

我知道您可以在 web、ios 和 android 中提取服务器时间戳 - 但是 Firebase 的新 Cloud Functions 函数呢?我不知道如何在那里获取服务器时间戳?用例是我想在电子邮件到达时为其添加时间戳。

On web it is Firebase.database.ServerValue.TIMESTAMP

在网络上是 Firebase.database.ServerValue.TIMESTAMP

But that doesn't seem to be available in the functions node server interface?

但这在功能节点服务器界面中似乎不可用?

I think it is late and I may be missing the point here...

我认为已经晚了,我可能在这里错过了重点......

EDIT

编辑

I am initializing like this

我是这样初始化的

admin.initializeApp(functions.config().firebase);
const fb = admin.database()

Then, it is being called like this..

然后,它被这样调用..

Firebase.database.ServerValue.TIMESTAMP

But, that is from a client side integration. On Functions, Firebase isn't initialized like this. I've tried

但是,这是来自客户端集成。在函数上,Firebase 不是这样初始化的。我试过了

admin.database().ServerValue.TIMESTAMP

and

fb.ServerValue.TIMESTAMP

回答by Frank van Puffelen

Since you're already using the admin SDK, the correct syntax is:

由于您已经在使用管理 SDK,正确的语法是:

admin.database.ServerValue.TIMESTAMP

回答by Paul

If you use the Firebase Admin SDK, here is the correct syntax (Checked 2019-08-27):

如果您使用 Firebase Admin SDK,这里是正确的语法(检查 2019-08-27):

const admin = require('firebase-admin');
// or
// import * as admin from 'firebase-admin';

// Using Cloud Firestore
admin.firestore.FieldValue.serverTimestamp()

// Using Realtime Database
admin.database.ServerValue.TIMESTAMP

回答by Spiral Out

Just to clarify for future readers:

只是为了向未来的读者澄清:

admin.database.ServerValue.TIMESTAMPreturns a non-null Objectand is a placeholder value for auto-populating the current timestamp. It doesn't contain the actual timestamp. The database will replace this placeholder when it will execute the command.

admin.database.ServerValue.TIMESTAMP返回一个non-null Object和是一个占位符值,用于自动填充当前时间戳。它不包含实际的时间戳。数据库将在执行命令时替换此占位符。

If you are using it inside a database.refthen it works just as you expect and is the preferred way to enter a timestamp :

如果您在 a 中使用它,database.ref那么它会按您的预期工作,并且是输入时间戳的首选方式:

var sessionsRef = firebase.database().ref("sessions");
sessionsRef.push({
startedAt: firebase.database.ServerValue.TIMESTAMP // this will write 'startedAt: 1537806936331`
});

But if you try to use it outside the database function (for example to return the time now or make some calculations) it will return an object that you cannot use it:

但是,如果您尝试在数据库函数之外使用它(例如返回现在的时间或进行一些计算),它将返回一个您无法使用它的对象:

console.log(firebase.database.ServerValue.TIMESTAMP) // this will return an [object Object]

See more about it in firebase.database.ServerValueand in this SO question.

firebase.database.ServerValue和这个SO question 中查看更多关于它的信息。

Date.now()works just fine outside a databasefunction if you want to use it for a calculation or any other general use.

Date.now()database如果您想将其用于计算或任何其他一般用途,则可以在函数之外正常工作。

console.log(Date.now()); // this will return 1537806936331

Both of them are using unix timewhich is number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, and it is irrelevant from the timezone. It is the same number on client and on server (...or almost:-). See unix time .

它们都使用unix timewhich 是自 1970 年 1 月 1 日星期四 00:00:00 协调世界时 (UTC) 以来经过的秒数,它与时区无关。它在客户端和服务器上是相同的数字(...或几乎:-)。请参阅unix 时间

回答by Bob Snyder

I'm new to node.js myself, but Date.now()works in my tests.

我自己是 node.js 的新手,但Date.now()在我的测试中有效。

Edit

编辑

I misunderstood you question--didn't realize you wanted to timestamp data you were storing in the Firebase database. I thought you simply wanted to get the time on the server that was running your cloud function. If you want to timestamp a received email being stored in the Firebase database, then using admin.database.ServerValue.TIMESTAMPis without question the best approach.

我误解了你的问题——没有意识到你想要为你存储在 Firebase 数据库中的数据加上时间戳。我以为您只是想在运行您的云功能的服务器上获得时间。如果您想为存储在 Firebase 数据库中的接收电子邮件添加时间戳,那么使用 admin.database.ServerValue.TIMESTAMP毫无疑问是最好的方法。

Just for my own education, I wrote the following function to see how the times compare. I would expect the times on the cloud function server and database server are synced to a very accurate time reference. When I run this function, the database timestamp typically within a hundred milliseconds of the Date.now()value. The database timestamp being a little later is reasonable, given that it takes the cloud function some time to connect to the database and perform the write.

只是为了我自己的教育,我编写了以下函数来查看时间比较。我希望云功能服务器和数据库服务器上的时间同步到一个非常准确的时间参考。当我运行这个函数时,数据库时间戳通常在Date.now()值的一百毫秒内。数据库时间戳稍晚是合理的,因为云函数需要一些时间来连接到数据库并执行写入。

exports.timeTest = functions.database.ref('/test/trigger')
    .onWrite(event => {

        const now= Date.now();
        console.log('now=', now);

        const timeVals = {
          dateNow : now,
          serverTimestamp : admin.database.ServerValue.TIMESTAMP
        };

        return event.data.ref.parent.child('times').update(timeVals);
    });

回答by ked

Using the following in the cloud function which is equivalent of Timestamp.now()on client side, this returns the current Timestamp

在客户端使用相当于Timestamp.now()的云函数中的以下内容,返回当前时间戳

admin.firestore.Timestamp.now()

But if you want to initialise Timestamp from Date object you can do it as follows

但是如果你想从 Date 对象初始化 Timestamp 你可以这样做

admin.firestore.Timestamp.fromDate(new Date())

And if you want to to initialise Timestamp for future or past date then first intialise the Date object either from parsing string or setting time that you want to set and pass it to Timestamp.fromDate()

如果你想为未来或过去的日期初始化时间戳,那么首先从解析字符串或设置你想要设置的时间初始化日期对象并将其传递给 Timestamp.fromDate()

var date = new Date('Wednesday, October 30, 2019 09:10 PM')
//or date = new Date('2014-06-30T06:40:53+05:30')
var timestamp = admin.firestore.Timestamp.fromDate(date)