Category: JS Objects
Updated

2023-07-12

Converting a Firestore Timestamp to a JS Date Object

Issue

How do I to convert a Firestore Timestamp to a JS Date Object to display it properly in Appsmith.

Example of timestamp:

{ 
"seconds": 1667964656, 
"nanos": 575000000 
}

Resolution

You can use a JavaScript function to convert the timestamp to milliseconds, then use moment(<milliseconds>).toDate() to convert it to a JS date object. Here is a JS Object you can use:

export default {
	convertTimestamp (timestamp) {
		//extract the seconds and nanos values from your Firestore timestamp object
		const { seconds, nanos } = timestamp;
		//combine the seconds and nanos values into a single timestamp in milliseconds
		const milliseconds = seconds * 1000 + nanos / 1e6;
		//use Moment.js to convert the timestamp to a date
		return moment(milliseconds).toDate();
	}
}

To display the date in a widget on Appsmith (for example, as the Default Date in a Date Picker widget), you can use the following snippet:

{{JSObject1.convertTimestamp(<your timestamp>)}}

where JSObject1 is the name of your JS Object.