简体   繁体   中英

Firebase firestore timestamp to Formatted Date

I am working on a firebase project and for displaying time regarding and entity, what i got is the timestamp. I am working on a react native project. How to convert the received timestamp to properly formatted date. This is the timestamp:

在此处输入图像描述

I have this time available in this.props.time , and so i tried this.props.time.toDate() but what i got was an error. 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 对象,然后按照您想要的方式操作它。

If you retrieve your data from the document, you can do this:

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

You can use https://momentjs.com/ to display

{moment(yourTimestamp.toDate()).format( ****format is inside the link above )}

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

NOT correct: new Date(time.seconds * 1000 + time.nanoseconds/1000)

Because, 在此处输入图片说明

For firestore v9 you can simply do like this.

You can use toDate() function along with toDateString() to display the date part alone.

const date = dateCreated.toDate().toDateString()
//Example: Friday Nov 27 2017

Suppose you want only the time part, then use the toLocaleTimeString()

const time = dateCreated.toDate().toLocaleTimeString('en-US')
//Example: 01:10:18 AM, the locale part 'en-US' is optional

And let's say you need to extract month and day from the date.

You simply do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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