Reputation: 11
I have a list with dates inside
$date = @('05-28-2020','09-30-2021')
I want to find the most recent date
I tried to convert string before comparat it :
[datetime]::ParseExact($date[0],'MM_dd_yyyy', $null)
But not working
Any ideas ?
Upvotes: 1
Views: 224
Reputation: 437513
You can directly cast your date-time strings to [datetime]
- no need for a ParseExact()
call - given that your input format is recognized by the invariant culture that PowerShell always uses in casts.
System.Linq.Enumerable.Max<T>()
allows you to find the maximum in a [datetime]
-typed enumerable.
Therefore:
$date = @('05-28-2020','09-30-2021') # Note: The @(...) enclosure isn't strictly needed.
[Linq.Enumerable]::Max([datetime[]] $date)
On a US-English system, the above yields Thursday, September 30, 2021 12:00:00 AM
, i.e. the default output formatting of the most recent date in the input, [datetime] '09-30-2021'
.
As for what you tried:
As has been mentioned, the only immediate problem with your ParseExact()
call was that you used _
instead of -
.
Also note that passing $null
as the third argument implies that the culture currently in effect is used during parsing (as reflected in [cultureinfo]::CurrentCulture
; this won't matter with numeric formatting sequences such as MM
, but it would with symbolic ones such as MMM
- and potentially even with unquoted placeholders :
and /
.
Upvotes: 1
Reputation: 79
$date = @('05-28-2020','09-30-2021')
$max = '01-01-1999'
$date | ForEach-Object {
if($_ -ge $max){
$max = $_
}
}
This should do the work.
Upvotes: 0