ReactJS: Firebase Sort date as string

Viewed 40

I have the DateFrom field in firebase being stored as a string "dd/mm/YY" (ie 20/05/2022)

When I try to sort this via:

useEffect(() => {
    const unsubscribe = firebase
      .firestore() //access firestore
      .collection("trips")
      .where("User", "==", user1)
      .orderBy("DateFrom", "asc")
      .onSnapshot(snapshot => {
        const listItemsTrips = snapshot.docs.map(doc => ({
          id: doc.id,
          ...doc.data()
        }));
        setItems(listItemsTrips);
      });
    return () => unsubscribe();
  }, []);
  return items;

it returns for the most part the correct results, but anything assigned to say 21/05/2023 will still appear after the 20/05/2022 date. How do I sort this string field by date? (through firebase console, doing a sort on the DateFrom field also shows in this order)

It looks to just be sorting by day & month and ignoring the year value?

1 Answers

You need to save the date in firebase as timestamp. Example:

yourRef
  .collection('you_colletcyion')
  .add({DateFrom: firebase.Timestamp.now()})

So

const unsubscribe = firebase
  .firestore() //access firestore
  .collection("trips")
  .where("User", "==", user1)
  .orderBy("DateFrom", "asc")

Then you can show the date by formatting it. Example with moment.js:

moment(user.DateFrom).locale('pt-br').format('LLL')
Related