Home > Software engineering >  Powershell Date math
Powershell Date math

Time:01-25

I am trying to determine when 1 set date is greater then or equal to a random date.

$2WeeksFuture = $null
# Calculate desired date 2 weeks from today
$2WeeksFuture = (Get-Date).AddDays(14)
# Convert to DateTime and apply formatting
$2WeeksFuture = (Get-Date -Date $2WeeksFuture -Format ("MM-dd-yy"))

$TimeMath | ForEach-Object {
    foreach ($User in $GSuspend ) {
        If ((Get-Date -Date $2WeeksFuture -Format ("MM-dd-yy")) -ge (get-date -date ($User.creationTime) -Format ("MM-dd-yy"))) {
            Write-Host "$(Get-Date -Date $2WeeksFuture -Format ("MM-dd-yy")) -ge $(get-date -date ($User.creationTime) -Format ("MM-dd-yy"))"
        }
    }
}

Wrong results

02-07-23 -ge 01-08-20
02-07-23 -ge 01-30-19
02-07-23 -ge 01-30-19
02-07-23 -ge 01-30-19
02-07-23 -ge 01-30-19
02-07-23 -ge 01-30-19
02-07-23 -ge 01-30-19

I have tried lots of combinations and it does not work.

CodePudding user response:

As @MathiasR.Jessen and @JeroenMostert mention, you already have DateTime object. e.g.

$2WeeksFuture = $null
# Calculate desired date 2 weeks from today
$2WeeksFuture = (Get-Date).AddDays(14)

PS C:\> $2WeeksFuture.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     DateTime                                 System.ValueType

Using the switch -Format ("MM-dd-yy") converts it into a String object:

PS C:\> (Get-Date -Date $2WeeksFuture -Format ("MM-dd-yy")).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

Performing a string comparison of dates will not work, the same way that putting in strings:

if("Tomorrow" -gt "Yesterday"){..}

Will not work. Instead, you should use the DateTime objects themselves (which have the right underlying conditional logic) to perform the comparison.

You have half the hard work done, converting the information/strings into DateTime objects. Now you only need to remove the formatting portion in the if statement to make sure you don't convert back into strings. e.g.

$2WeeksFuture = $null
# Calculate desired date 2 weeks from today as a DateTime object
$2WeeksFuture = (Get-Date).AddDays(14)

$TimeMath | ForEach-Object {
    foreach ($User in $GSuspend ) {
        If ($2WeeksFuture -ge (Get-Date -Date ($User.creationTime))) {
            Write-Host "$(Get-Date -Date $2WeeksFuture -Format ("MM-dd-yy")) -ge $(get-date -date ($User.creationTime) -Format ("MM-dd-yy"))"
        }
    }
}
  • Related