简体   繁体   中英

PowerShell get latest string date

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?

  • 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 , ie 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 / .

switch your _ to - and it will work: 在此处输入图像描述

$date = @('05-28-2020','09-30-2021')
$max = '01-01-1999'
$date | ForEach-Object {
    if($_ -ge $max){
        $max = $_
    }
}

This should do the work.

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