简体   繁体   English

如何在 React 的 firebase firestore 中获取/生成当前时间戳

[英]How to get/generate current Timestamp in firebase firestore in React

I am using Firebase Firestore database in my current project and have to add documents from my front-end react for this i need current timestamp.我在我当前的项目中使用 Firebase Firestore 数据库,并且必须从我的前端添加文档,为此我需要当前时间戳。

import * as firebase from "firebase";
import React, {useState} from 'react';

const [time, setTime] = useState({''}) //here i need current timestamp from firebase.

well you need to import firestore from firebase, don't use firebase.firestore.FieldValue.serverTimeStamp it won't work那么你需要从 firebase 导入 firestore,不要使用 firebase.firestore.FieldValue.serverTimeStamp 它不会工作

here is the working example这是工作示例

import {firestore} from "firebase";

const timestamp = firestore.FieldValue.serverTimestamp();
firebase.initializeApp(firebaseConfig);
const projectFirestore = firebase.firestore();
const timestamp = firebase.firestore.FieldValue.serverTimestamp;

firebase.initializeApp(firebaseConfig); firebase.initializeApp(firebaseConfig); const timestamp = firebase.firestore.FieldValue.serverTimestamp; const timestamp = firebase.firestore.FieldValue.serverTimestamp;

please also note that as much as @shubham Takode answer is true, firebase firestore current timestamp doesn't get populated on the client side, so it will do you no good trying to use it in the react useState() management.另请注意,尽管@shubham Takode 的回答是正确的,但客户端不会填充 firebase firestore 当前时间戳,因此尝试在 react useState() 管理中使用它对您没有好处。

import * as firebase from "firebase";
import React, {useState} from 'react';

firebase.firestore
    .collection('user')
    .doc('userid1')
    .set({
           username: "first user",
           email: "user@email.com",
           time: firebase.firestore.FieldValue.serverTimestamp() // This sets a placeholder in your record that get authomatically populated with the serverTime once it gets to your firestore db.
    }).then(/*do somethings on success*/).catch(err => {/*do somethings on err*/})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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