Prime Prime - 3 months ago 23
PowerShell Question

how to compare two custom dates in powershell v2.0

Is it possible to compare 2 custom dates. Am trying check if variables hold date1 is lessthan date2, if so, report saying date1 is older date.

I getting both dates from a. date1 from log file and date2 from application itself

now, both date1 and date2 are in required format ie,

$Date1 = Tue,Aug 16, 2016 12:40:03
$Date2 = Mon,Aug 22, 2016 16:33:02


my next step is compare these 2 dates and report if date1 is older date compare to Date2, which I don't know how to proceed.. Any help/ideas is much appreciated.

Thanks to Pete and Ansgar Wiechers

updated working Code :

$Date1DateTime = [DateTime]::ParseExact($Date1,'ddd,MMM d, yyyy, HH:mm:ss',[Globalization.CultureInfo]::InvariantCulture); $Date2DateTime = [DateTime]::ParseExact($Date2,'ddd,MMM d, yyyy, HH:mm:ss',[Globalization.CultureInfo]::InvariantCulture); $Date1DateTime -lt $Date2DateTime

Answer

You can only compare date strings if the string sort order is the same as the date sort order. For instance, date strings in ISO format are comparable:

2016-08-16T12:40:03
2016-08-22T16:33:02

Date strings in your custom format are not, because T comes after M, but August 16 should actually come before August 22:

Tue,Aug 16, 2016 12:40:03
Mon,Aug 22, 2016 16:33:02

If you don't have the date strings in ISO format it's usually better to parse them into actual DateTime values (as @PetSerAl suggested), particularly if your reference value is originally a DateTime anyway.

$fmt     = 'ddd,MMM d, yyyy, HH:mm:ss'
$culture = [Globalization.CultureInfo]::InvariantCulture

$Date1 = Get-Date $LogFileDate
$val   = (b2b.exe -readparams $param | Select-Object -Skip 1 -First 1) -split '='
$Date2 = [DateTime]::ParseExact($val[1], $fmt, $culture)

if ($Date1 -lt $Date2) {
  ...
}