Search code examples
angularfirebasegoogle-cloud-firestoreangularfire

How to manipulate Firestore extracted data to convert timestamp to date


I'm trying to find a way to convert the timestamp extracted from Firestore to a regular date. Here is the code that stores the result of my query in an array :

Here is my getActiveItemsList() function from the myFirestoreDatabaseService service:

getActiveItemsList() {
    return this.afs.collection('GRD_active').valueChanges({idField: 'id'});
}

And here is the actual code where I store the data returned from Firestore :

this.myFirestoreDatabaseService.getActiveItemsList().subscribe(data => {
    this.displayedDataSource = data;
});

One of the fields of the documents in the GRD_active collection is a timestamp. Therefore, the data being stored in the displayedDataSource variable is the following :

Screenshot

How can I iterate over every document stored in the array to only reformat the date to a standard format? In other words, perform some kind of data manipulation to all the timeEntered and timeCompleted fields of every entry in the array in order to convert them to regular dates.

Thank you very much for your support


Solution

  • just map the array with the rx map operator:

    return this.afs.collection('GRD_active').valueChanges({idField: 'id'}).pipe(
      map(data => data.map(d => {
        d.timeEntered = new Date(d.timeEntered.seconds * 1000);
        d.timeCompleted = new Date(d.timeCompleted.seconds * 1000);
        return d;
      }))
    );
    

    the time is stored as a timestamp in seconds, so just multiply by 1000 to convert to ms and create a JS native Date object with that value.