如何在Firebase云函数中访问firestore.Timestamp
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:
First, make sure you have the Firebase Admin SDK installed (if you haven't already):
npm install firebase-adminImport 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(); }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();
- Defining types (if using TypeScript):
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

