Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare dates from a string in PowerShell [duplicate]

Tags:

powershell

$Deldate = "19-06-2018"
$Newdate = "04-06-2018"

I need to check which date is bigger.

if ($Deldate -ge $NewDate) {
    write-host "NewDate is bigger"
} 
else {
    write-host "Deldate is bigger"
}

This is not working for me, and it looks like the format is not "System.DateTime". I'm getting the date values are from an external CSV file. How do I find a solution for this?

like image 389
rpr Avatar asked Jun 07 '26 17:06

rpr


1 Answers

You should be able to cast the strings that you have created to the "datetime" type like so:

$Deldate = "19-06-2018"
$Newdate = "04-06-2018"

$Deldate = [datetime]::ParseExact("$Deldate", 'dd-MM-yyyy', $null)
$Newdate = [datetime]::ParseExact("$Newdate", 'dd-MM-yyyy', $null)

if ($Deldate -ge $NewDate) {
    write-output "NewDate is bigger than or equal to"
}
else {
    write-output "Deldate is bigger"
}

This returns the correct result. You can't simply use the Get-Date cmdlet, since the -Date required parameter also requires that the parameter be of type "DateTime", so you first have to cast the strings to the DateTime type.

like image 99
Bryce McDonald Avatar answered Jun 10 '26 10:06

Bryce McDonald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!