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))
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))
5 Answers
Reset to default 14You can create a Date object with new Date(time.seconds * 1000 + time.nanoseconds/1000000)
then manipulate it the way you want.
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"
new Date(this.props.time.seconds * 1000)
– VilleKoo Commented Nov 26, 2019 at 7:21