Forum Discussion
How to find nearest date?
I currently have a list of dates in a slicer in single select:
- Today's Date (Ex: 2 May 2022)
- 29 April 2022
- 31 Mar 2022
- 28 Feb 2022
- 31 Jan 2022
- 31 Dec 2021
- 30 Nov 2021
- 29 Oct 2021
- 30 Sep 2021
- All the way to 2011.
The list consist of today's date and the date for end of each month. However, for months that ends on a weekend, it will have the date on Friday instead of the weekend. Example: April 2022, ends on 30 April 2022, but list has 29 April 2022.
What I'm trying to do is when a date is chosen in the slicer, I want to subtract 3 months from that date and find the nearest possible date (this is necessary due to some dates ending on Friday instead of weekend issue).
I have come up with this code:
3MthsAgo Average Score =
VAR _NumMonthsAgo = 3
VAR _CurrentDate = VALUES('Sheet1'[Date])
VAR _XMonDate = DATE(YEAR(_CurrentDate), MONTH(_CurrentDate) - _NumMonthsAgo, DAY(_CurrentDate))
VAR _XMonYear = YEAR(_XMonDate)
VAR _XMonMonth = MONTH(_XMonDate)
RETURN
CALCULATE(
AVERAGE( Sheet1[Score] ),
ALL( Sheet1[Score] ),
YEAR(Sheet1[Date]) = _XMonYear,
MONTH(Sheet1[Date]) = _XMonMonth)The first four lines of code allow me to subtract 3 months from the current date chosen in the slicer. However, this does not work for all cases, because of the date ending on Friday instead of weekend issue. Also, sometimes it gives the wrong month when subtracting 3 months from the date due to differing number of days in each month:
I think the way to solve this is to compare compare _XMonDate (the 3 months ago date) with the dates in the slicer and find the date that is the nearest to it? Do you know how this can be done?
Thank you!
Deermeat , I've answered your other thread that may help you with this issue.
2 Replies
- Deermeat
Resolver I
Yup! Thank you very much for your help.
Link for others to reference: https://community.powerbi.com/t5/Desktop/How-to-subtract-3-months-from-a-Date-then-find-nearest-possible/m-p/2486574/thread-id/885245