繁体   English   中英

Firebase 格式化日期的 firestore 时间戳

[英]Firebase firestore timestamp to Formatted Date

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

在此处输入图像描述

我在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(time.seconds * 1000 + time.nanoseconds/1000000)创建一个Date 对象,然后按照您想要的方式操作它。

如果您从文档中检索数据,您可以这样做:

// 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);
}

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

{moment(yourTimestamp.toDate()).format( ****format 在上面的链接内)}

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

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

因为, 在此处输入图片说明

对于 firestore v9,您可以简单地这样做。

您可以使用 toDate() function 和 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"

暂无
暂无

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

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