You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firebase云函数中访问firestore.Timestamp

How to Access Firestore Timestamp in Node.js (Firebase Admin/Functions)

Got it, I ran into this exact confusion when switching between the frontend Firebase SDK and the Admin SDK in Node.js—totally get why you're stuck! The key here is that the Node-side Admin SDK structures things differently than the frontend SDK.

Here's the fix:

The Timestamp class lives under the firebase-admin package's firestore module, not the functions object. Here's how to get it working:

  1. First, make sure you have the Firebase Admin SDK installed (if you haven't already):

    npm install firebase-admin
    
  2. Import and initialize the Admin SDK (usually at the top of your functions file):

    import * as admin from 'firebase-admin';
    
    // Initialize once to avoid duplicate app errors
    if (!admin.apps.length) {
      admin.initializeApp();
    }
    
  3. Access Timestamp via admin.firestore.Timestamp:
    You can now use it just like you did on the frontend, but with this new path. For example:

    • Defining types (if using TypeScript):
      interface Event {
        startDate: admin.firestore.Timestamp;
        endDate: admin.firestore.Timestamp;
      }
      
    • Converting a Date to Timestamp:
      const currentTime = admin.firestore.Timestamp.fromDate(new Date());
      
    • Converting a Timestamp back to a Date:
      const eventDate = eventDoc.data().startDate.toDate();
      

Why this works (and why functions didn't have it):

The firebase-functions package is only for defining and deploying Cloud Functions—it doesn't include Firestore's data types or utilities. All Firestore-related tools in the Node environment live under the firebase-admin SDK, which is designed for server-side access to Firebase services.

If you're using CommonJS (instead of ES modules), the syntax is almost identical:

const admin = require('firebase-admin');

if (!admin.apps.length) {
  admin.initializeApp();
}

const timestamp = admin.firestore.Timestamp.fromDate(new Date());

That should get you up and running with Timestamps in your Node/Functions code!

内容的提问来源于stack exchange,提问作者Matthew Mullin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:24:08