Firebase Firestore 时间戳转换为格式化日期。

8
我可以帮您进行翻译。以下是需要翻译的内容:

我正在进行一个Firebase项目,在显示实体相关时间时,我得到的是时间戳。我正在进行一个React Native项目。如何将接收到的时间戳转换为格式正确的日期。 这是时间戳:

enter image description here

我有这段时间可用于this.props.time,所以我尝试了this.props.time.toDate(),但是我得到了一个错误。Invariant Violation: Objects are not valid as a React child(found: Tue Nov 26 2019 11:51:58 GMT+05:30(Indian Standard Time))

我想你可以将其转换为类似于 new Date(this.props.time.seconds * 1000) 的格式 - VilleKoo
1
我认为它已经被正确转换了,但是错误在于显示它。你能提供一下你如何显示它的代码吗? - Kishan Bharda
1
@KishanBharda 已经修复了!我需要将它转换为字符串。我的做法是:new Date( this.props.time.seconds * 1000 + this.props.time.nanoseconds / 1000, ).toLocaleDateString() - FortuneCookie
5个回答

12
你可以使用 new Date(time.seconds * 1000 + time.nanoseconds/1000000) 创建一个 Date 对象,然后按照你想要的方式进行操作。

1
我按照以下方式操作后,它成功了:new Date( this.props.time.seconds * 1000 + this.props.time.nanoseconds / 1000, ).toLocaleDateString() - FortuneCookie

1
你可以使用 https://momentjs.com/ 来显示

{moment(yourTimestamp.toDate()).format( ****格式在上述链接中 )}


1

正确的写法: new Date(time.seconds * 1000 + time.nanoseconds/1000000)

不正确的写法: new Date(time.seconds * 1000 + time.nanoseconds/1000)

因为, 这里输入图片描述


1
如果您从文档中检索数据,可以这样做:
// time.toDate()
convertDate(doc.data().time.toDate())

const convertDate = (date) => {
    // whatever formatting you want to do can be done here
    var d = date.toString()
    return d.substr(0, 21);
}

0
对于Firestore v9,您可以简单地按照以下方式进行操作。
您可以使用toDate()函数与toDateString()一起使用,仅显示日期部分。
const date = dateCreated.toDate().toDateString()
//Example: Friday Nov 27 2017

假设您只想要时间部分,则使用toLocaleTimeString()函数。
const time = dateCreated.toDate().toLocaleTimeString('en-US')
//Example: 01:10:18 AM, the locale part 'en-US' is optional

假设您需要从日期中提取月份和日期。

您只需执行以下操作:

const date = new Date(Date.now());
date.toLocaleString('en-US', {month: 'short'}); // {month:'long'}
Expected Output: "Jan"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接