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

前端 未结 7 1215
轮回少年
轮回少年 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: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/

提交回复
热议问题