Javascript 反应-显示firestore时间戳
我试图弄清楚如何在react应用程序中显示firestore时间戳 我有一个firestore文档,其中有一个名为createdAt的字段 我试图将其包含在输出列表中(在这里提取相关位,这样您就不必通读整个字段列表) } 我还尝试将其添加到map语句中,但得到一个错误,表明user.get不是函数Javascript 反应-显示firestore时间戳,javascript,reactjs,firebase,google-cloud-firestore,unix-timestamp,Javascript,Reactjs,Firebase,Google Cloud Firestore,Unix Timestamp,我试图弄清楚如何在react应用程序中显示firestore时间戳 我有一个firestore文档,其中有一个名为createdAt的字段 我试图将其包含在输出列表中(在这里提取相关位,这样您就不必通读整个字段列表) } 我还尝试将其添加到map语句中,但得到一个错误,表明user.get不是函数 {user.get().then(function(doc) { console.log(doc.data().createdAt.toDate());}
{user.get().then(function(doc) {
console.log(doc.data().createdAt.toDate());}
)}
它生成与上面相同的错误消息
下一次尝试
在试图找到一种在Firestore中记录日期的方法并允许我读回日期时,出现了一件奇怪的事情,那就是当我以一种形式更改提交处理程序以使用此公式时:
handleCreate = (event) => {
const { form } = this.formRef.props;
form.validateFields((err, values) => {
if (err) {
return;
};
const payload = {
name: values.name,
// createdAt: this.fieldValue.Timestamp()
// createdAt: this.props.firebase.fieldValue.serverTimestamp()
}
console.log("formvalues", payload);
// console.log(_firebase.fieldValue.serverTimestamp());
this.props.firebase
.doCreateUserWithEmailAndPassword(values.email, values.password)
.then(authUser => {
return this.props.firebase.user(authUser.user.uid).set(
{
name: values.name,
email: values.email,
createdAt: new Date()
// .toISOString()
// createdAt: this.props.firebase.fieldValue.serverTimestamp()
},
{ merge: true },
);
// console.log(this.props.firebase.fieldValue.serverTimestamp())
})
.then(() => {
return this.props.firebase.doSendEmailVerification();
})
// .then(() => {message.success("Success") })
.then(() => {
this.setState({ ...initialValues });
this.props.history.push(ROUTES.DASHBOARD);
})
});
event.preventDefault();
};
用于在数据库中记录日期的
firestore条目的形式如下所示:
//This code gets all the users and logs it's creation date in the console
docRef.get().then(function(docRef) {
if (docRef.exists && docRef.data().createdAt) {
console.log("User created at:", docRef.data().createdAt.toDate());
}
})
我正在尝试在此组件中显示日期:
class UserList extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
users: [],
};
}
componentDidMount() {
this.setState({ loading: true });
this.unsubscribe = this.props.firebase
.users()
.onSnapshot(snapshot => {
let users = [];
snapshot.forEach(doc =>
users.push({ ...doc.data(), uid: doc.id }),
);
this.setState({
users,
loading: false,
});
});
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const { users, loading } = this.state;
return (
<div>
{loading && <div>Loading ...</div>}
<List
itemLayout="horizontal"
dataSource={users}
renderItem={item => (
<List.Item key={item.uid}>
<List.Item.Meta
title={item.name}
description={item.organisation}
/>
{item.email}
{item.createdAt}
{item.createdAt.toDate()}
{item.createdAt.toDate().toISOString()}
</List.Item>
// )
)}
/>
</div>
);
}
}
export default withFirebase(UserList);
我得到一个错误,上面写着:
TypeError:无法读取未定义的属性“toDate”
基于在其他字段中读回同一文档中记录的条目的能力,我希望这些条目中的任何一个都能产生输出,即使它的格式不是我想要的。那不会发生
下一次尝试
以Waelmas为例,我尝试按照说明进行操作,但在第一步中我们没有得到相同的响应。当Walemas根据.toDate()扩展名获取输出时,我会得到一个错误,说toDate()不是函数
{user.get().then(function(doc) {
console.log(doc.data().createdAt.toDate());}
)}
与Firebase文档一致,我尝试了:
const docRef = this.props.firebase.db.collection("users").doc("HnH5TeCU1lUjeTqAYJ34ycjt78w22");
docRef.get().then(function(docRef) {
if (doc.exists) {
console.log("Document createdAt:", docRef.createdAt.toDate());
}
})
这会产生一系列语法错误,我无法找到解决方法
下一次尝试
然后,我尝试创建一个新表单,看看是否可以在没有用户表单的身份验证方面的情况下对此进行探索
我有一个表单,它将输入作为:
this.props.firebase.db.collection("insights").add({
title: title,
text: text,
// createdAt1: new Date(),
createdAt: this.props.firebase.fieldValue.serverTimestamp()
})
其中,在上一个表单中,new Date()尝试在数据库中记录日期,在本例中,createdAt和createdAt1的两个字段都生成相同的数据库条目:
没有。它呈现一个错误,该错误表示:
TypeError:无法读取未定义的属性“Date”
这似乎和我有同样的问题,但并没有涉及他们如何显示他们存储的日期值
这似乎被数组错误消息卡住了,但似乎已经解决了如何使用createdAt.toDate()显示日期的问题,因此firestore将日期存储为具有秒和纳秒的对象。如果您想要创建用户的时间,那么可以引用
user.createdAt.nanoseconds
。这将返回一个unix时间戳
您希望如何在应用程序中显示日期?如果您想获得一个日期对象,那么可以将时间戳传递到日期构造函数中,如so
newdate(user.createdAt.nanoseconds)
。就个人而言,我喜欢使用库来处理时间。当您从Firestore获得时间戳时,它们是以下类型:
要将其转换为普通时间戳,可以使用.toDate()函数
{user.get().then(function(doc) {
console.log(doc.data().createdAt.toDate());}
)}
例如,对于以下文档:
const docRef = db.collection("users").doc("[docID]");
docRef.get().then(function(docRef) {
if (docRef.exists) {
console.log("user created at:", docRef.data().createdAt.toDate());
}
})
我们可以使用类似于:
db.collection('[COLLECTION]').doc('[DOCUMENT]').get().then(function(doc) {
console.log(doc.data().[FIELD].toDate());
});
输出结果如下所示:
2019-12-16T16:27:33.031Z
现在,为了进一步处理该时间戳,您可以将其转换为字符串,并使用正则表达式根据需要对其进行修改
例如:(我在这里使用Node.js)
将为您提供如下输出:
//This code gets all the users and logs it's creation date in the console
docRef.get().then(function(docRef) {
if (docRef.exists && docRef.data().createdAt) {
console.log("User created at:", docRef.data().createdAt.toDate());
}
})
如何将日期发送到Firestore:
import firebase from 'firebase/app';
// ..........
// someObject is the object you're saving to your Firestore.
someObject.createdAt: firebase.firestore.Timestamp.fromDate(new Date())
function mapMonth(monthIndex) {
const months = {
0: 'jan',
1: 'feb',
2: 'mar',
3: 'apr',
4: 'may',
5: 'jun',
6: 'jul',
7: 'aug',
8: 'sep',
9: 'oct',
10: 'nov',
11: 'dec'
};
return months[monthIndex];
}
// ..........
// Here you already read the object from Firestore and send its properties as props to this component.
return(
<LS.PostDate_DIV>
Published on {mapMonth(props.createdAt.toDate().getMonth()) + ' '}
of {props.createdAt.toDate().getFullYear()}
</LS.PostDate_DIV>
);
}
如何回读:
import firebase from 'firebase/app';
// ..........
// someObject is the object you're saving to your Firestore.
someObject.createdAt: firebase.firestore.Timestamp.fromDate(new Date())
function mapMonth(monthIndex) {
const months = {
0: 'jan',
1: 'feb',
2: 'mar',
3: 'apr',
4: 'may',
5: 'jun',
6: 'jul',
7: 'aug',
8: 'sep',
9: 'oct',
10: 'nov',
11: 'dec'
};
return months[monthIndex];
}
// ..........
// Here you already read the object from Firestore and send its properties as props to this component.
return(
<LS.PostDate_DIV>
Published on {mapMonth(props.createdAt.toDate().getMonth()) + ' '}
of {props.createdAt.toDate().getFullYear()}
</LS.PostDate_DIV>
);
}
函数映射月(monthIndex){
常数月={
0:'一月',
1:‘二月’,
2:‘三月’,
3:‘四月’,
四:"五月",,
五:"六月",,
6:‘七月’,
7:‘八月’,
8:‘九月’,
9:‘10月’,
10:‘11月’,
11:‘12月’
};
返回月份[孟欣德斯];
}
// ..........
//在这里,您已经从Firestore读取了对象,并将其属性作为道具发送到此组件。
返回(
在{mapMonth(props.createdAt.toDate().getMonth())+''上发布
{props.createdAt.toDate().getFullYear()}
);
}
基本上,当您执行createdAt.toDate()
时,您会得到一个JS日期对象
我一直这样用它
发件人:
这将根据用户的系统日期创建数据。
如果您需要确保数据库中的所有内容都按时间顺序存储(没有用户系统设置的错误系统日期错误),那么应该使用服务器时间戳。将使用Firestore DB内部日期系统设置日期
如果用户的文档ID设置了
createdAt
属性,请尝试以下操作:
const docRef = db.collection("users").doc("[docID]");
docRef.get().then(function(docRef) {
if (docRef.exists) {
console.log("user created at:", docRef.data().createdAt.toDate());
}
})
在访问文档属性之前,调用.data()
方法很重要
请注意,如果访问未设置createdAt
属性的用户的docRef.data().createdAt.toDate()
,则将获得TypeError:无法读取未定义的属性“toDate”
因此,如果您的集合中有任何用户未定义createdAt
属性。在获取属性之前,应该实现一个逻辑来检查用户是否具有createdAt
属性。您可以这样做:
//This code gets all the users and logs it's creation date in the console
docRef.get().then(function(docRef) {
if (docRef.exists && docRef.data().createdAt) {
console.log("User created at:", docRef.data().createdAt.toDate());
}
})
我以前遇到过这样的问题:嵌套对象属性在列表中不能正确呈现,其中
item.someProp
被视为对象,但item.someProp.somesubop
不能用item.someProp
中的somesubop
值解决
因此,为了回避这个问题,为什么不在创建用户对象时将时间戳计算为普通日期对象(或所需的显示格式)
this.unsubscribe=this.props.firebase
.users()
.onSnapshot(快照=>{
让用户=[];
snapshot.forEach(doc=>
设docData=doc.data();
docData.createdAt=docData.createdAt.toDate();
push({…docData,uid:doc.id})
{new Date(user.createdAt._seconds * 1000).toLocaleDateString("en-US")}
createdAt: this.props.firebase.Timestamp.fromDate(new Date())