简体   繁体   中英

How to store date in Firestore from client side without importing firebase-admin?

I want to use something like serverTimestamp method on client side but to do that I need to include the firebase-admin package which would increase the client bundle size.

import * as firebaseAdmin from "firebase-admin";
if (!firebaseAdmin.apps.length) {
  firebaseAdmin.initializeApp();
}

const firebaseTimestamp = firebaseAdmin.firestore.FieldValue.serverTimestamp();

const initDate = firebaseAdmin.firestore.Timestamp.fromDate(
    new Date(Date.UTC(0, 0, 0, 0, 0, 0))
  );

Is there any lightweight solution to access firebase timestamp methods from client side?

I'm not sure if I could ditch servertimestamp and go with new Date() as it's related to current timezone. I want to store time in Firestore (from client side) which is not relative to any timezone and I should be able to query firestore based on that Date parameter later.

ref: https://firebase.google.com/docs/reference/node/firebase.firestore.Timestamp

You must not import Firebase Admin SDK on client side. It requires service account to run and has admin privileges ie does not obey any security rules and has full access to your Firebase Project.

You can add timestamp using client SDK too:

firebase.firestore.FieldValue.serverTimestamp()

You can read more about this in the documentation

Alternatively you can use UNIX Timestamps and you won't have the timezone issues.

It is the number of seconds that have elapsed since the Unix epoch, minus leap seconds; the Unix epoch is 00:00:00 UTC on 1 January 1970;

const timestamp = Date.now()

Then you can use the JS Date object to format it in any format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM