Recently I came across a Power Apps solution that needed to sort a collection by a date column. In this post the pains of sorting by date fields and how to work around them.

Sort a collection by date fields

Now there are a few annoying features with dates. Empty date fields have always been a bit of an issue when writing items to SharePoint or Dataverse, but how about collections with Blank date fields?

In my example Power Apps app I’ve created a button, that generates a collection using the following code:

ClearCollect(colMyData,
   {Title: "Today", MyDate: Today() },
   {Title: "Unknown", MyDate: Blank() },
   {Title: "Yesterday", MyDate: DateAdd(Today(), -1, TimeUnit.Days)}
)

Then I created three galleries. The first gallery shows the data as I’ve created my collection.

The second gallery sorts the data by the date column in a Descending direction. Finally the 3rd gallery shows the data in Ascending order.

What is happening here? The record with the empty Date column always appears at the bottom of my gallery.

Sort a Collection by a date column
Collection sorted by date column

It looks like sorting by date columns will only take records with values set into account. My empty dates are simply ignored and placed at the bottom of the list. This is something that we need to fix.

Fixing the date sorting

I’m updating the way I’m creating my collection. Now I’m converting the date to text values.

ClearCollect(colMyData,
  {Title: "Today", MyDate: Text(Today(),"yyyy/mm/dd") },
  {Title: "Unknown", MyDate: Text(Blank(), "yyyy/mm/dd") },
  {Title: "Yesterday", MyDate: Text(DateAdd(Today(), -1, TimeUnit.Days),"yyyy/mm/dd")}
)

Now as I present the data in my three galleries the records appear as expected.

Collection sorted by date column as text
Collection sorted by date column as text

We can of course optimize the above code a bit. I wouldn’t really want to convert my date columns to text columns. Using the AddColumns function it is most likely better to create a text version of the column to my existing collection.


Discover more from SharePains

Subscribe to get the latest posts sent to your email.

Related Posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.