Home > Software engineering >  How to get all dates of the week based on week number using powershell?
How to get all dates of the week based on week number using powershell?

Time:02-03

I'm using powershell 7.x and want to create an array of dates in a week based on the weeknumber. I'm able to generate the array and find the whole week dates but how can I get the date values returned in the output?

I have used [System.Globalization.ISOWeek]::ToDateTime([Int32] year,[Int32] week number,[DayOfWeek]:Monday), to fetch the days of the week. Is there a better and optimal way to fetch all the dates in the array based on the week number?

Here's the code below:

function fetchWeekDates {
    $output = @{ Monday =[System.Globalization.ISOWeek]::ToDateTime(2022,1,[DayOfWeek]::Monday)}
    $output  = @{ Tuesday=[System.Globalization.ISOWeek]::ToDateTime(2022,1,[DayOfWeek]::Tuesday)}
    $output  = @{ Wednesday =[System.Globalization.ISOWeek]::ToDateTime(2022,1,[DayOfWeek]::Wednesday)}
    .
    .
    .
    $output  = @{ Sunday =[System.Globalization.ISOWeek]::ToDateTime(2022,1,[DayOfWeek]::Sunday)}

    return $output
}

Expected output:

Output
------- 
01-03-2022
01-04-2022
01-05-2022
01-06-2022
01-07-2022
01-08-2022
01-09-2022

CodePudding user response:

The following function accepts a week number, and optionally a year (defaults to the current) and the day of the week that is considered the start of a week (defaults to Monday), and outputs [datetime] instances representing all days in that week.

function Get-DatesInWeekNumber {
  param(
    [Parameter(Mandatory)]
    [int] $WeekNumber,
    [int] $Year = (Get-Date).Year,
    [DayOfWeek] $FirstDayOfWeek = 'Monday'
  )
  $date = [Globalization.ISOWeek]::ToDateTime($Year, $WeekNumber, $FirstDayOfWeek)
  0..6 | ForEach-Object { $date.AddDays($_) }
}

Note the use of the [datetime] type's .AddDays() method.

Sample call, which formats the [datetime] instances as desired:

Get-DatesInWeekNumber -WeekNumber 1 -Year 2022 |
  ForEach-Object ToString MM-dd-yyyy

This produces the output as shown in your question.

  • Related