如何在 Firebase 的云函数中获得服务器时间戳?

我知道你可以在 web、 ios 和 android 中使用服务器时间戳,但是新的 Firebase 云功能怎么样呢?我不知道怎么把服务器的时间戳弄到那里?用例是我想在邮件到达时给它加上时间戳。

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

但是在函数节点服务器接口中似乎不可用?

我觉得现在很晚了,我可能没抓住重点。

剪辑

我像这样初始化

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

然后,它被称为这样. 。

Firebase.database.ServerValue.TIMESTAMP

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

admin.database().ServerValue.TIMESTAMP

还有

fb.ServerValue.TIMESTAMP
54481 次浏览

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

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.TIMESTAMP is without question the best approach.

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.

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);
});

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

admin.database.ServerValue.TIMESTAMP

If you use the Firebase Admin SDK, here is the correct syntax (Checked 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

Just to clarify for future readers:

admin.database.ServerValue.TIMESTAMP returns a non-null Object and 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.

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

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.ServerValue and in this SO question.

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

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

Both of them are using unix time which 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 .

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

admin.firestore.Timestamp.now()

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

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()

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)

It's in the documentation August 16, 2020.

https://cloud.google.com/firestore/docs/manage-data/add-data#server_timestamp

// Get the `FieldValue` object
const FieldValue = admin.firestore.FieldValue;


// Create a document reference
const docRef = db.collection('objects').doc('some-id');


// Update the timestamp field with the value from the server
const res = await docRef.update({
timestamp: FieldValue.serverTimestamp()
});

Here's how I used it in my code:

const createUserDoc = (user) => {
const FieldValue = admin.firestore.FieldValue
return db.collection('users').doc(user.uid).set({
memberSince: FieldValue.serverTimestamp(),
})
}

Depends on use case

case 1

you want to set document field to server timestamp

Example can be

user {
email: "example.com",
lastUpdated: admin.firestore.FieldValue.serverTimestamp(),
}

Note serverTimestamp returns a non-null Object and 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

*Returns a sentinel used with set(), create() or update() to include a server-generated timestamp in the written data.

@return The FieldValue sentinel for use in a call to set(), create() or update().*

case 2

you want use server time stamp for your functions logic

if (currentTime == 6pm) // TODO: send push notifications
else // TODO: do nothing

for that you might want to do something like

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

good reads: https://bigcodenerd.org/firebase-server-timestamp-cloud-functions/

You can try:

const timestamp = admin.firestore.Timestamp.now();

console.log("Show current timestamp, in Milliseconds= " + Date.now());