# weekinmonth in powershell starts on Sunday…

This April month is full of surprises! Not only I did not have the opportunity to trick my colleagues on Sunday April first, but I had some bug of my code due to the start of the week.

[int](get-date).dayofweek and (Get-WmiObject Win32_LocalTime).dayofweek both refer Sunday as day 0.

``` PS> get-date Wednesday, 11. April 2012 18:31:52 PS C:\svn> [int](get-date).dayofweek 3 PS C:\svn> (Get-WmiObject Win32_LocalTime).dayofweek 3 ```

Consistently and unfortunately for me, the week does start on Sunday. And not on Monday.

To get week ending on Sunday, lets add 6 for Monday (5 for Tuesday, and so on) to dayofweek and get the 7-modulo
``` PS> (6+(get-date).dayofweek)%7 2 ```
Ok, now Mon=0, Tue=1, Wed=2, etc…

Substract it from day of month to truncate to Monday
``` PS> (get-date).day - (6+(get-date).dayofweek)%7 9 ```

First day of current week is Monday 9th

Now add 5 to get the first Day of month between 0 and 6
Divide by 7…
add 1 to get first week=1 (and not 0).

Truncate
``` PS> [math]::floor(((get-date).day - (6+(get-date).dayofweek)%7 + 5)/7)+1 3 ```

Which slicely differs from weekinmonth when 1st of month is Sunday !
``` PS> (Get-WmiObject Win32_LocalTime).weekinmonth 2 ```

Pfeww…

## By Laurent Schneider

Oracle Certified Master

1. Anonymous says:

Wow! Thank you very much!
ðŸ™‚

2. I wanted to run something on the first Friday of every month and used “weekinmonth” thinking that would be 1 for the first 7 days etc. Since it starts on Sunday, that was a mistake. For my purposes this works:

\$datetest = get-date