0

Date Time objects allow us to perform actions like this:

$CurrentDate = Get-Date
$TextDate = get-date -date "02/10/2016"

if ($TextDate -lt $CurrentDate){
    Write-Host "True"
}
else {
    Write-Host "False"
}

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

Following the same logic, why does the following code output 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 returns True.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Corey
  • 133
  • 2
  • 11

3 Answers3

2

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 because 6 comes after 1, your 6 -lt 11-test returns false.

Frode F.
  • 52,376
  • 9
  • 98
  • 114
2

Formatted dates are strings, not integers. The string "6" is after the string "11".

This would be the most correct way to do this:

First, decide what the "first week of the year" actually means:

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

Then, decide 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 your 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 }

Note that if you want a full ISO 8601 week, it's somewhat more complicated.

Bacon Bits
  • 30,782
  • 5
  • 59
  • 66
1

Both $TextDate and $CurrentDate are of type [string] so what you are evaluating is '6' -lt '11' which will return false. Operators are based on the left side type in PowerShell. So in order to force an integer comparison modify your expression as under

if ([int]$TextDate -lt $CurrentDate)
{ 
   Write-Host "True" 
} 
else 
{
   Write-Host "False" 
}
Nana Lakshmanan
  • 741
  • 3
  • 6