Date Day of Week Logic in PowerShell

Date Time objects allow us to do the following:

$CurrentDate = Get-Date $TextDate = get-date -date "02/10/2016" if ($TextDate -lt $CurrentDate){ Write-Host "True" } else { Write-Host "False" } 

This displays "True" because $ TextDate is less than $ CurrentDate.

Following the same logic, why is the following code outputting false?

 $CurrentDate = Get-Date -UFormat %V $TextDate = Get-Date -date "02/10/2016" $TextDate = Get-Date -date $TextDate -UFormat %V if ($TextDate -lt $CurrentDate){ Write-Host "True" } else { Write-Host "False" } 

The only difference is that we are comparing the week of the year. If you change the comparison to -gt , the code will return True.

0
source share
3 answers

Formatted dates are strings, not integers. Line "6" is located after line "11" .

This would be the most correct way to do this:

First determine what the "first week of the year" means:

 $CalendarWeekRule = [System.Globalization.CalendarWeekRule]::FirstDay; #$CalendarWeekRule = [System.Globalization.CalendarWeekRule]::FirstFourDayWeek; #$CalendarWeekRule = [System.Globalization.CalendarWeekRule]::FirstFullWeek; 

Then determine which day of the week is the first day of the week:

 $FirstDayOfWeek = [System.DayOfWeek]::Sunday; #$FirstDayOfWeek = [System.DayOfWeek]::Monday; #Any day is available 

Then you can get the correct week number:

 $Today = (Get-Date).Date; $TodayWeek = [cultureinfo]::InvariantCulture.Calendar.GetWeekOfYear($Today, $CalendarWeekRule, $FirstDayOfWeek); $TargetDate = Get-Date -Date "2016-02-10"; $TargetWeek = [cultureinfo]::InvariantCulture.Calendar.GetWeekOfYear($TargetDate, $CalendarWeekRule, $FirstDayOfWeek); if ($TargetWeek -lt $TodayWeek) { $true } else { $false } 

Please note that if you want to spend a full week of ISO 8601, it’s a bit more complicated .

+2
source

Because you are comparing string objects.

 (Get-Date -UFormat %V).GetType().FullName System.String 

When comparing strings using -gt and -lt it sorts the strings and, since 6 comes after 1, your test 6 -lt 11 returns false.

+2
source

Both $ TextDate and $ CurrentDate are of type [string], so you evaluate to "6" -lt '11', which will return false. Operators are based on the left type in PowerShell. Therefore, to make the integer comparison change your expression as in

 if ([int]$TextDate -lt $CurrentDate) { Write-Host "True" } else { Write-Host "False" } 
+1
source

Source: https://habr.com/ru/post/1245359/


All Articles