最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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?

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?

Share Improve this question edited Jul 24, 2019 at 0:23 Frank van Puffelen 599k85 gold badges889 silver badges859 bronze badges asked Jul 24, 2019 at 0:06 J.DJ.D 4591 gold badge6 silver badges17 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 13

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(...)

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(...))

Import

import * as firebase from 'firebase/app';

and use

created_at = firebase.firestore.FieldValue.serverTimestamp();   
发布评论

评论列表(0)

  1. 暂无评论