简体   繁体   中英

Date Time day of the week comparison logic in PowerShell

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.

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.

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 .

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" 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM