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

node.jsFirebaseFirebase Realtime-DatabaseGoogle Cloud-FunctionsFirebase Admin

node.js Problem Overview


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.

On web it is 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

admin.database().ServerValue.TIMESTAMP

and

fb.ServerValue.TIMESTAMP

node.js Solutions


Solution 1 - node.js

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

admin.database.ServerValue.TIMESTAMP

Solution 2 - node.js

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

Solution 3 - node.js

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 .

Solution 4 - node.js

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

Solution 5 - node.js

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/

Solution 6 - node.js

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)

Solution 7 - node.js

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

Solution 8 - node.js

You can try:

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

Solution 9 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustin HandleyView Question on Stackoverflow
Solution 1 - node.jsFrank van PuffelenView Answer on Stackoverflow
Solution 2 - node.jsPaulView Answer on Stackoverflow
Solution 3 - node.jsSpiral OutView Answer on Stackoverflow
Solution 4 - node.jsBob SnyderView Answer on Stackoverflow
Solution 5 - node.jssultanmyrzaView Answer on Stackoverflow
Solution 6 - node.jskedView Answer on Stackoverflow
Solution 7 - node.jsCollin ThomasView Answer on Stackoverflow
Solution 8 - node.jsShiva YadavView Answer on Stackoverflow
Solution 9 - node.jsGeneView Answer on Stackoverflow