Power Fx: Calculate | Calculate Days in a Month


Power Fx is the Excel-like, formula language of the Power Platform. Akin to Microsoft Excel, most of the functions are only reasonably powerful on their own. When they’re combined though, they become much more awe-inspiring. For example, calculating the number of days in a month.


Calculating this, makers only need a handful of functions and there are just a few steps:


For ease, use the With() function to create some sub-formulas. To start with, get a DateValue() and store it in an inline variable. After that, use the inline variable and store the first of the current month in another line variable, using the Month() and Year() functions. Now, 32 days are added to this new variable, clearly pushing the calendar into next month. Using the Month(), Year(), and DateValue() functions again, get the first day of the new month. Finally, subtract 1 day to get the last day of the previous month and use the Day() function to parse the numerical value:


E.g., Power Fx snippet.

With({
    // Provided date
    vDate: DateValue("8/14/2023")
    },
    With({
        // Get first day of the month
        vMonthFirst: DateValue(
            $"{Month(vDate)}/1/{Year(vDate)}"
        )
        },
        With({
            // Move into next month
            vMonthNext: (vMonthFirst + 32)
            },
            With({
                // Get first day of month
                firstOfNextMonth: DateValue(
                    $"{Month(vMonthNext)}/1/{Year(vMonthNext)}"
                )
                },
                // Get final day of last month
                $"{Day(firstOfNextMonth - 1)}"
            )
        )
    )
)

E.g., Power Fx result.

Figure 1 - Power Apps canvas app example.
Figure 1Power Apps canvas app example.

Conclusion:
Being a formula programming language, Power Fx shines best when functions are combined and/ or nested.

“Rule-following, legal precedence, and political consistency are not more important than right, justice and plain common-sense.”

W. E. B. Du Bois

#BlackLivesMatter

One thought on “Power Fx: Calculate | Calculate Days in a Month

  1. Pingback: Power Fx: Date Picker | Calculate Day of the Year | console.log('Charles');

Leave a comment