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

49,711

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 .

Solution 4

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

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/

Share:
49,711

Related videos on Youtube

Justin Handley
Author by

Justin Handley

Justin Handley is an online marketing and business automation expert as well as a PHP programmer, WordPress enthusiast, and javascript / react experimenter who runs a managed hosting and security solution for WordPress at http://managedwp.rocks

Updated on July 08, 2022

Comments

  • Justin Handley
    Justin Handley almost 2 years

    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
    
    • Frank van Puffelen
      Frank van Puffelen about 7 years
      As far as I know ServerValue.TIMESTAMP is equally available in Cloud Functions for Firebase. Can you share the minimal code that reproduces the problem?
    • Justin Handley
      Justin Handley about 7 years
      Hi @FrankvanPuffelen - I edited the original with an example of my initialization and what isn't working.
  • Justin Handley
    Justin Handley about 7 years
    And does Date.now() get the node server time, or the time from the client's computer to do it's calculation? Or does it use some standardized clock? If I set my computer time to one time, did Date.now() then set it to a different time and did Date.now() would I get two different results?
  • Bob Snyder
    Bob Snyder about 7 years
    @JustinHandley: Updated my answer. Date.now() is the time on the server running your cloud function. It is completely independent of the time on any client computer.
  • Justin Handley
    Justin Handley about 7 years
    This is the simple answer I was looking for - thanks @frank-van-puffen
  • vir us
    vir us over 6 years
    how do you print timestamp in milliseconds with this? admin.database.ServerValue.TIMESTAMP returns an object { '.sv': 'timestamp' }, which I believe is a placeholder
  • Frank van Puffelen
    Frank van Puffelen over 6 years
    It is indeed a placeholder. To get the actual value, listen on the location that you write to.
  • Qorbani
    Qorbani over 6 years
    Working like a charm :-) Thanks.
  • Luke Pighetti
    Luke Pighetti over 5 years
    admin.database.ServerValue.TIMESTAMP is the only acceptable solution when you are using Firebase Rules to test that this == now (Bolt)
  • John T
    John T about 5 years
    Best answer for a newbie! :)
  • DevAS
    DevAS almost 5 years
    hello, when i write timestamp and save it into DB i got this in cloud functions message: 'Messaging payload contains an invalid value for the "notification.timestamp" property. Values must be strings.' @SpiralOut
  • Spiral Out
    Spiral Out almost 5 years
    @DevAS Try posting a new question with more details about your code. But Notification.timestamp is not firebase db keyword. Maybe use firebase.database.ServerValue.TIMESTAMP
  • ThdK
    ThdK almost 5 years
    I think for cloud firestore is has to be: admin.firestore.FieldValue.serverTimestamp()
  • Shajeel Afzal
    Shajeel Afzal about 4 years
    firestore.FieldValue.serverTimestamp() is not working on nodejs firebase functions.
  • Maduranga E
    Maduranga E almost 4 years
    Can this be different from the value in a regular JS Date?
  • August Kimo
    August Kimo over 2 years
    2021: admin.firestore.Timestamp.now()