Reputation: 459
Trying to convert from javascript date to firestore timestamp throws
TypeError: Cannot read property 'Timestamp' of undefined
I tried it in 2 ways:
const admin = require('firebase-admin');
const db = admin.firestore();
const timestamp = db.Timestamp.fromDate(new Date(date));
const firebase = require('firebase');
const timestamp = firebase.firestore.Timestamp.fromDate(new Date(date));
date used as a param in new Date is of this format: "2017-01-29".
Expected result: firestore timestamp.
Actual result: TypeError: Cannot read property 'Timestamp' of undefined
Note: db nor firebase are null or undefined.
Is there a definitive way of creating firestore timestamp from javascript date object?
Upvotes: 6
Views: 4400
Reputation: 317928
Your second example isn't using the Firebase Admin SDK at all - that's the Firebase web client SDK.
If you're working with the Admin SDK prior to v11:
const admin = require('firebase-admin');
const timestamp = admin.firestore.Timestamp.fromDate(...)
Or v11:
const { Timestamp } = require('firebase-admin/firestore')
const timestamp = Timestamp.fromDate(...)
Upvotes: 13
Reputation: 186
The accepted answer doesn't work in the latest version of firebase-admin (v11). admin.firestore.Timestamp is undefined. Here is how I got it working in the new version:
const { Timestamp } = require('firebase-admin/firestore')
const timestamp = Timestamp.fromDate(new Date(...))
Upvotes: 7
Reputation: 1448
Import
import * as firebase from 'firebase/app';
and use
created_at = firebase.firestore.FieldValue.serverTimestamp();
Upvotes: -3