• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Get week from date - Power BI desktop

Ok, I've changed my approach. Went with custom function route.
Name it fnAdjWkNum
Code:
(cDate as date)=>
let
    sDate = #date(Date.Year(cDate), 1, 1),
    dList = List.Select(List.Dates(sDate, Duration.Days(#date(Date.Year(cDate)+2,1,1) - sDate) + 1, #duration(1,0,0,0)), each Date.DayOfWeek(_, Day.Sunday)=0 and Date.Day(_)<=7),
    sList = List.Generate(()=>0, each _ < List.Count(dList), each _ + 1, each if Date.Day(dList{_}) <=4 then dList{_} else Date.AddDays(dList{_},-7)),
    mStart = List.Max(List.Select(sList, each _<= cDate)),
    mEnd = List.Min(List.Select(sList, each _> cDate)),
    mList = List.Dates(mStart, Duration.Days(mEnd - mStart), #duration(1,0,0,0)),
    wList = Record.Field(List.Last(List.Generate(
                            ()=> [Date=null, WkNum=null, y=0, x=-1],
                            each [x] < List.Count(mList) and ([Date]=null or [Date]<=cDate),
                            each [Date=mList{x}, WkNum=Number.RoundUp((x+1)/7), y=[y]+1, x=[x]+1],
                            each [[Date],[WkNum],[y]])), "WkNum")
in
    wList

In your table with date column (make sure it is in Date data type). Then add custom column and invoke custom function.

Ex:
=fnAdjWkNum([Date column name])

This will return week number. So you just have to concatenate it with "Week".
Ex:
Code:
="Week"&Number.ToText(fnAdjWkNum([Date column name]),"0")

EDIT: You could simplify the wList part a bit. But I purposefully left additional info in returned list. So, if something goes wrong, you can change Record.Field to obtain more info on the record returned to help in trouble shooting.
For get this in excel or vba ? instead of maintain Week table we can use formula or function ? please suggest.
Sorry not opening new thread for this..
 
You don't need to maintain week table with custom function approach.
Just add custom column to your table and use date column as argument in the function.

NOTE: However, for any sort of analysis involving time intelligence, it is recommended that you have date/calendar dimension table. Many of time intelligence function in DAX depends on it (ParallelPeriod etc).
 
Last edited:
Back
Top