Powershell - Get date from week and weekday

Viewed 306

I have a file containing 'year', 'week-number', and 'weekday', (example - '2022', '42', '4',) 42 represents week 42 of 2022, and the 4 represents tuesday. A 7 would represent sunday.

The first week is to be considered the first days until sunday, regardless if it is 7 days or not. Same principle for the last week. That week can also contain fewer than 7 days.

How can i translate this to a date like 'yyyyMMdd'?

Thanks

1 Answers

Note:

  • The following uses .NET's System.DayOfWeek enumeration to identify weekdays, which means that Sunday is 0, Monday is 1, ..., and Saturday is 6.

  • If your weekday-numbering scheme differs (which is what it sounds like), you'll have to map it onto the above.

# Convert the strings (representing CSV input) to numbers.
[int] $year, [int] $week, [int] $weekday =  '2022', '42', '4'

# The day of the week you consider the start of a calendar week.
$startOfWeekDay = [DayOfWeek]::Monday

# Calculate the start of calendar week 1 for the given year:
# The Monday on or preceding Jan 1
# Note: This date may therefore fall into the previous year.
$Jan1 = [datetime]::new($year, 1, 1)
$StartOfWeek1 = $Jan1.AddDays(-((7 + $Jan1.DayOfWeek-$startOfWeekDay) % 7))

# Calculate the start of the target calendar week.
$StartOfTargetWeek = $StartOfWeek1.AddDays($week * 7)

# Calculate the target date by determining the desired weekday
# inside the target week.
$TargetDate = $StartOfTargetWeek.AddDays((7 + $weekday-$startOfWeekDay) % 7)
$TargetDateString = $TargetDate.ToString('yyyyMMdd')

# Output *for display* both the intermediate results and the final one.
[pscustomobject] @{
  Jan1 = ($Jan1 | Out-String).Trim()
  StartOfWeek1 = ($StartOfWeek1 | Out-String).Trim()
  StartOfTargetWeek = ($StartOfTargetWeek | Out-String).Trim()
  TargetWeekDay = [DayOfWeek] $weekday
  TargetDate = ($TargetDate | Out-String).Trim()
  TargetDateString = $TargetDateString
} | Format-List

Output:

Jan1              : Saturday, January 1, 2022 12:00:00 AM
StartOfWeek1      : Monday, December 27, 2021 12:00:00 AM
StartOfTargetWeek : Monday, October 17, 2022 12:00:00 AM
TargetWeekDay     : Thursday
TargetDate        : Thursday, October 20, 2022 12:00:00 AM
TargetDateString  : 20221020
Related