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

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

Solution 1:

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

admin.database.ServerValue.TIMESTAMP

Solution 2:

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:

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 .