How do I convert a Firestore date/Timestamp to a JS Date()?
The constructor for a JavaScript's Date
doesn't know anything about Firestore's Timestamp
objects — it doesn't know what to do with them.
If you want to convert a Timestamp
to a Date
, use the toDate()
method on the Timestamp
.
How to convert Firestore Timestamp to Date() - Firestore V9
How do I check if a field is an instance of Timestamp?You can import
Timestamp
class from Firestore package.How do I convert an instance of Timestamp into Date() object?This method exists on a Timestamp object.
import { Timestamp } from "firebase/firestore"
const timeObj = new Timestamp();
console.log(timeObj instanceof Timestamp)
console.log(timeObj.toDate());
convert firestore timestamp to date into different format
You should use the toDate()
method of the Firestore Timestamp
:
So, you would do the following:Convert a Timestamp to a JavaScript Date object. This conversion
causes a loss of precision since Date objects only support millisecond
precision.Returns
Date
JavaScript Date object representing the same point in time as this
Timestamp, with millisecond precision.
var timestampDate = change.doc.data().timestamp.toDate();
console.log(timestampDate);
Then, you need to format this date as desired. The easiest is to use a dedicated library like moment.js
, as follows:<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
// ...
<script>
// ...
var timestampDate = change.doc.data().timestamp.toDate();
var m = moment(timestampDate );
var mFormatted = m.format(); // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds)
console.log(mFormatted );
// ...
</script>
Other possibilities for formatting a date with moment.js
are to be found here. how to convert firebase timestamp to only date and time in html?
Firestore sdk toDate()
returns a javascript Date object. So you can format it the way you need from there. There are no other formatting options from the Firestore sdk.
There is more information on the Firestore Timestamp here: https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp
For formatting, one option (of many in JavaScript) is dateformat. It is much smaller than something like moment.js
or dayjs
and sufficient if all you are doing is formatting date/time output for display.
To format string for your desired output would be:ddd mmm dd yyyy HH:MM:SS
How to convert timestamp firestore to date string and display in antd table
UPDATE FIXED
i don't know why antd table cant convert timestamp directly in renderCell or render. so i choose to set data from firestore like this.
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()
}
},[])
userColumnconst 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,
},
]
Method for coverting all Firestore Timestamps in a snapshot to JS dates?
I don't think there is any global method for this, but I think its easy to create a function that will analyze snapshot and change it. It's not very complicated. In node.js I have done it like this:
function globalToData (snapshot) {
for (const field in snapshot)
if (snapshot[field] instanceof Firestore.Timestamp) {
snapshot[field] = snapshot[field].toDate()
}
else if (snapshot[field] instanceof Object) {
globalToData (snapshot[field]);
}
return snapshot;
};
if you get DocumentSnapshot
as ex. snap you can call it like:globalToData(snap.data())
This should convert all Timestamps in all levels of Document snapshot ( I tested to 3rd level of nesting mixed map and array). We do not have your solution, but you can implement this somewhere in the middle of your app. Convert milliseconds to Firestore date
You can use fromMillis( ) method from firestore.timestamp
which can create new timestamp from the given number of milliseconds.
firestore.Timestamp.fromMillis(milliseconds)
You can refer these documents for more details firestore timestamp from milliseconds and Firestore Timestamp
Related Topics
How to 'Await' on an Rx Observable
Rendering to Js with Jinja Produces Invalid Number Rather Than String
How Does Setinterval and Settimeout Work
Quickest Way to Pass Data to a Popup Window I Created Using Window.Open()
How to Handle Oncut, Oncopy, and Onpaste in Jquery
Attaching Click Event to a Jquery Object Not Yet Added to the Dom
Regular Expression for Ip Address Validation
Event.Path Is Undefined Running in Firefox
JavaScript Timestamp to Relative Time
Javascript: Dynamically Creating Variables for Loops
How to Detect When a Tab Is Focused or Not in Chrome with JavaScript
JavaScript Add Method to Object
How to Export Excel Files Using JavaScript
I Can't Reference an Image in Next.Js
What Is the Most Efficient Way to Reverse an Array in JavaScript
How to Find a Reason Angularjs "Argument 'Myctrl' Is Not a Function, Got Undefined"