Skip to content

Instantly share code, notes, and snippets.

@robkb
Last active March 7, 2017 00:57
Show Gist options
  • Save robkb/9f0594213188ad5b70fa823e5ece8377 to your computer and use it in GitHub Desktop.
Save robkb/9f0594213188ad5b70fa823e5ece8377 to your computer and use it in GitHub Desktop.
M functions to create ISO 8601 Week & Year from dates

DEPRECATED: see this updated fork

from https://social.technet.microsoft.com/Forums/en-US/2a85c825-c75b-4622-98a1-25547dec49c8/enhancement-request-iso-week-number?forum=powerquery

(DAX's weeknum(x, 21) doesn't give the ISO Year)

InsertISOYear = Table.AddColumn(
    previousstepname,
    "ISOYear",
    each Date.Year(
        Date.AddDays(
            [Date],
            3 - Date.DayOfWeek([Date], 1)
        )
    ),
    type number
),

InsertRefDate = Table.AddColumn(
    InsertISOYear,
    "RefDate",
    each #date([ISOYear], 1, 3)
),

InsertISOWeek = Table.AddColumn(
    InsertRefDate,
    "ISOWeek",
    each Number.IntegerDivide(
        Duration.Days( [Date] - [RefDate] ) + Date.DayOfWeek([RefDate], 0) + 6,
        7
    ),
    type number
),

InsertWeekInt = Table.AddColumn(
    InsertISOWeek,
    "WeekInt",
    each [ISOYear] * 100 + [ISOWeek],
    type number
),

InsertCalendarWeek = Table.AddColumn(
    InsertWeekInt,
    "WeekInCalendar",
    each Number.ToText([ISOYear]) & Number.ToText([ISOWeek], "-W00")
),

RemovedColumns = Table.RemoveColumns(
    InsertCalendarWeek,
    {"RefDate"}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment