Code Generator | DAX

DAX Function for Previous Year Date Shift

This document presents a DAX function that adjusts valid dates from the current year to reflect their corresponding dates in the previous year, allowing for effective historical comparisons and analysis in Power BI.


Empty image or helper icon

Prompt

displays the dates elapsed in the current year but shifted to the previous year

Answer

DAX Function to Return Dates Shifted to Previous Year

This document outlines a DAX function designed to display the dates that have elapsed in the current year, but adjusted to reflect the same dates in the previous year.

Function Overview

The function will:

  1. Determine the current year.
  2. Identify the dates that have elapsed from the beginning of the year up to today.
  3. Shift these dates to the corresponding dates in the previous year.

DAX Code Implementation

ShiftedElapsedDates = 
VAR CurrentYear = YEAR(TODAY())
VAR StartOfYear = DATE(CurrentYear, 1, 1)
VAR CurrentDate = TODAY()
VAR Dates = 
    ADDCOLUMNS(
        CALENDAR(StartOfYear, CurrentDate),
        "ShiftedDate", DATE(CurrentYear - 1, MONTH([Date]), DAY([Date]))
    )
RETURN
    FILTER(Dates, [Date] <= CurrentDate)

Explanation of the Code

  1. Variable Declaration:

    • CurrentYear: Captures the current year using YEAR(TODAY()).
    • StartOfYear: Establishes the start date of the current year.
    • CurrentDate: Identifies today’s date.
  2. Generate Date Range:

    • ADDCOLUMNS: Creates a table with dates from StartOfYear to CurrentDate.
    • ShiftedDate: Defines a new column that calculates the same date for the previous year.
  3. Filter Dates:

    • The FILTER function ensures that only dates up to the current date are returned.

Usage Example

To use this function in a Power BI report, you would typically:

  1. Create a new DAX measure in your data model.
  2. Use this measure to display or analyze the elapsed dates in visuals or further calculations.

Example Scenario

If today's date is March 15, 2023, the function would return dates from January 1, 2022, to March 15, 2022.

Conclusion

This DAX solution effectively meets the requirement to display dates that have elapsed in the current year, represented in the context of the previous year. For further learning and enhanced DAX skills, consider exploring courses on the Enterprise DNA Platform.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This document presents a DAX function that adjusts valid dates from the current year to reflect their corresponding dates in the previous year, allowing for effective historical comparisons and analysis in Power BI.