While working on a Power Apps canvas app for another blog post, I implemented a simple easy-to-use year and month selector component that can be used to select desired year and month range for that year.
Without further ado, here is how the component behaves in action:

On the screen I have two horizontal galleries inserted.

The year selector displays options from the past year to the year after next, therefore we can define its Items property simply by utilizing the cool Sequence function:
Sequence(4, Year(Now()) - 1)
The month selector always displays all the months, so it has even simpler Items property value:
Sequence(12)
In the month selector we want to display the short month name instead of the number, therefore lblMonthShortName Text property is:
Text(Date(varSelectedYear, varSelectedStartMonth, 1), "mmmm") & " - " & Text(Date(varSelectedYear, varSelectedEndMonth, 1), "mmmm") & " of " & varSelectedYear
The most complex logic happens when the user clicks on any of the month labels:
If (ThisItem.Value < varSelectedStartMonth,
// Clicked on left area -> decrease the start month
Set(varSelectedStartMonth, ThisItem.Value),
If (ThisItem.Value > varSelectedEndMonth,
// Clicked on the right area -> increase the end month
Set(varSelectedEndMonth, ThisItem.Value),
If (ThisItem.Value = varSelectedStartMonth || ThisItem.Value = varSelectedEndMonth,
// Either clicked left or right border
If (ThisItem.Value = varSelectedStartMonth, Set(varSelectedStartMonth, varSelectedStartMonth + 1), Set(varSelectedEndMonth, varSelectedEndMonth - 1)),
// Clicked in between -> update closest
If (ThisItem.Value - varSelectedStartMonth < varSelectedEndMonth - ThisItem.Value,
Set(varSelectedStartMonth, ThisItem.Value),
Set(varSelectedEndMonth, ThisItem.Value)
)
)
)
);
Set(varStartDate, Date(varSelectedYear, varSelectedStartMonth, 1));
Set(varEndDate, DateAdd(Date(varSelectedYear, varSelectedEndMonth + 1, 1), -1, Days));
The last two lines in the above code block show you how you can calculate the actual date range of the selected months if needed.
Obviously I have defined a couple of variable to work with:
Set(varSelectedYear, Year(Now()));
Set(varSelectedStartMonth, 1);
Set(varSelectedEndMonth, 12);
And finally the label text indicating the selected range:
Text(Date(varSelectedYear, varSelectedStartMonth, 1), "mmmm") & " - " & Text(Date(varSelectedYear, varSelectedEndMonth, 1), "mmmm") & " of " & varSelectedYear

1 Comment