Date.IsInPreviousNMonths

Updated on

Date.IsInPreviousNMonths is a Power Query M function that indicates whether the given date(time) value occurs during the previous number of months, as determined by the system. The function returns a boolean value (true or false).

Compatible with: Power BI Service Power BI Desktop Excel Microsoft 365

Syntax

Date.IsInPreviousNMonths(
   dateTime as any,
   months as number,
) as nullable logical

Description

Date.IsInPreviousNMonths determines if a given value (of type date, datetime, or datetimezone) is within a specified number of months before the current system date and time, excluding current month values. It requires a months argument.

Examples

Let’s explore two straightforward examples to understand how the Date.IsInPreviousNMonths function works.

Identifying Dates in the Previous N Months

Let’s say you have a calendar table and you want to add a column that indicates true for dates that fall within the previous n months. You can do this using the Date.IsInPreviousNMonths function on your [Date] column. Here, n is the number of months you want to check.

Date.IsInPreviousNMonths( [Date], n ) // Output depends on [Date] column and n

This expression returns true for any date in the [Date] column that falls within the previous n months.

To check if your [Date] falls within the last 4 months you can then use:

Date.IsInPreviousNMonths( [Date], 4 )

For example, if today is July 6, 2024, this function will return true for all rows with dates between March 1, 2024, and June 30, 2024. Here’s a screenshot showing this:

How to use the Date.IsInPreviousNMonths Function in Power Query M

You can see that dates within the previous 3 months are marked with true.

Using the Current Date and Time

If we retrieve the current date (generated by DateTime.FixedLocalNow) and shift it back 2 months, we can check if it falls within the last three months by using:

// Output: true
Date.IsInPreviousNMonths( Date.AddMonths( DateTime.FixedLocalNow(), -2 ), 3 )

Other functions related to Date.IsInPreviousNMonths are:

Contribute » | Contributors: Rick de Groot
Microsoft documentation: https://learn.microsoft.com/en-us/powerquery-m/date-isinpreviousnmonths

2023-2024 © BI Gorilla. All rights are reserved. Information from Microsoft docs is property of Microsoft Corp. | Privacy Policy