[英]How to convert timestamp firestore to date string and display in antd table
首先,我有来自 firestore 的 antd 表和数据源,其中包含一些字段并包括时间戳字段。 我的数据运行良好并显示在 antd 表中,问题只是时间戳值不显示。
这是代码
获取数据
useEffect(() => {
const unsub = //some code
//some code
//some code
.onSnapshot((querySnapshot) => {
let list = []
querySnapshot.forEach((doc) => {
list.push({
id: doc.id,
...doc.data(),
})
})
setData(list)
setLoading(false)
})
return () => {
unsub()
}
},[])
数据结构
[{id: '1', name: 'Gie', timestamp: {seconds: 1651770000, nanoseconds: 0}, {id: '2', name: 'Yud', timestamp: {seconds: 1652370000, nanoseconds: 0}]
时间戳格式自动来自 Firestore 时间戳字段
蚂蚁表
<TableData
pagination={{
position: ['bottomRight'],
pageSize: 10,
total: 0,
showTotal: (total) => `Total ${total} item`,
}}
onChange={handleTable}
columns={userColumns}
dataSource={filterTable == null ? data : filterTable}
rowKey={(record) => record.id}
rowSelection={rowSelection}
loading={loading}
size="middle"
/>
antd 表用户列
const userColumns = [
{//other column
//other column
},
{
title: 'Timestamp',
dataIndex: 'timestamp',
key: 'timestamp',
width: '12%',
renderCell: (params) => {
return
<div>{params.timestamp.toDate()}</div> //doesnt work and not show anything
},
sorter: (a, b) => a.timestamp - b.timestamp,
sortOrder: sortedInfo.columnKey === 'timestamp' && sortedInfo.order,
},
]
我正在尝试另一个代码但不起作用
{新日期(params.timestamp).toDateString()}
{新日期(params.timestamp).toLocaleDateString('id-ID')}
{new Date(params.timestamp.seconds * 1000).toLocaleDateString('id-ID')}
但是当我尝试使用地图进行转换时,效果很好
const date = data.map((item) => {timestamp: new Date(item.timestamp.seconds * 1000).toLocaleDateString('id-ID')})
console.log(date) //输出:2022 年 5 月 6 日
更新已修复
我不知道为什么antd table 不能直接在renderCell 或render 中转换时间戳。 所以我选择像这样从firestore设置数据。
useEffect(() => {
const unsub = //some code
//some code
//some code
.onSnapshot((querySnapshot) => {
let list = []
querySnapshot.forEach((doc) => {
list.push({
id: doc.id,
name: doc.data().name,
timestamp: doc.data().timestamp,
dateString: new Date(doc.data().timestamp.seconds * 1000).toLocaleDateString('id-ID')
})
})
setData(list)
setLoading(false)
})
return () => {
unsub()
}
},[])
用户列
const userColumns = [
{//other column
//other column
},
{
title: 'Date',
dataIndex: ['dateString', 'timestamp'],
key: 'timestamp',
width: '12%',
render: (e, params) => {
return
<div>{params.dateString}</div>
},
sorter: (a, b) => a.timestamp - b.timestamp,
sortOrder: sortedInfo.columnKey === 'timestamp' && sortedInfo.order,
},
]
如果不知道您将什么传递给实际的<Table />
组件,就很难说清楚。 检查传递给带有timestamp
dataIndex 的列的内容是否正确。
我感觉你的数据看起来像
{
....
timestamp: "",
...
}
在这种情况下,它应该是params.toDate()
而不是params.timestamp.toDate()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.