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

前端 未结 7 1164
轮回少年
轮回少年 2020-12-03 00:12

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

相关标签:
7条回答
  • 2020-12-03 00:51

    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);
        });
    
    0 讨论(0)
  • 2020-12-03 00:52

    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(),
        })
    }
    
    0 讨论(0)
  • 2020-12-03 00:53

    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)
    
    0 讨论(0)
  • 2020-12-03 00:56

    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 .

    0 讨论(0)
  • 2020-12-03 00:56

    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/

    0 讨论(0)
  • 2020-12-03 01:04

    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
    
    0 讨论(0)
提交回复
热议问题