J.D
J.D

Reputation: 459

How to save date as Timestamp in firestore using firebase-admin?

Trying to convert from javascript date to firestore timestamp throws

TypeError: Cannot read property 'Timestamp' of undefined

I tried it in 2 ways:

  1. Using firebase-admin
const admin = require('firebase-admin');
const db = admin.firestore();
const timestamp = db.Timestamp.fromDate(new Date(date));
  1. Using firebase.firestore:
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

Answers (3)

Doug Stevenson
Doug Stevenson

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

Pete Shilling
Pete Shilling

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

ztvmark
ztvmark

Reputation: 1448

Import

import * as firebase from 'firebase/app';

and use

created_at = firebase.firestore.FieldValue.serverTimestamp();   

Upvotes: -3

Related Questions