1

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
  • I think the problem is with the string datatype of the field. Try to store it as a date instead of string, it would work as expected. Commented May 23, 2022 at 11:21

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

3 Comments

Even better would be to use Firestore's native Timestamp type: DateFrom: Timestamp.now()
I ended up using: DateFrom: firebase.firestore.Timestamp.fromDate(new Date(datefrom)) ... I show these items within a map using item.DateFrom ... but doing so returns the error "Uncaught Error: Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}). If you meant to render a collection of children, use an array instead." ... I did try DateFrom: item.DateFrom.toDate() ... this did not work either
Try with new Date().getTime() first. After it works, then change the way to do it for the correct way, using the firebase Timestamp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.