Category: JS Objects
Resource links
Updated

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 a timestamp to milliseconds and then use Moment.js to convert it to a JavaScript Date object. Below is the sample JS Object code to achieve this:

export default {
	//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), use the following snippet:

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

In this snippet:

  • JSObject1 is the name of your JavaScript Object.
  • <your timestamp> should be replaced with the actual timestamp you want to convert. To test the code, you can use:
  • { 
    "seconds": 1667964656, 
    "nanos": 575000000 
    }