Sort a date string in ddmmyyyy format

Hello guys,

I have a array of strings which are actually date in dd/mm/yyyy format. How can I sort them and get the output in dd/mm/yyyy format?

Here is what I have tried. Please suggest if there is a better/alternate way to achieve the result.

PS [21:28:34] D:\> $a = "17/01/2015","25/12/2013","16/11/2014"

PS [21:28:37] D:\> $a
17/01/2015
25/12/2013
16/11/2014

PS [21:28:39] D:\> Get-Culture

LCID             Name             DisplayName                                                                                                                                        
----             ----             -----------                                                                                                                                        
2057             en-GB            English (United Kingdom)                                                                                                                           



PS [21:28:47] D:\> Get-UICulture

LCID             Name             DisplayName                                                                                                                                        
----             ----             -----------                                                                                                                                        
1033             en-US            English (United States)                                                                                                                            



PS [21:28:49] D:\> $a | sort
16/11/2014
17/01/2015
25/12/2013

PS [21:28:58] D:\> $a | ForEach-Object {[datetime]::Parse("$_",(Get-Culture))} | sort

25 December 2013 00:00:00
16 November 2014 00:00:00
17 January 2015 00:00:00



PS [21:29:01] D:\> $a | ForEach-Object {[datetime]::Parse("$_",(Get-Culture)) -f "dd/mm/yyyy" } | sort
01/17/2015 00:00:00
11/16/2014 00:00:00
12/25/2013 00:00:00

PS [21:29:04] D:\> 

Expected output

17/01/2015
16/11/2014
25/12/2013

Try this:

$a | ForEach-Object {[datetime]::Parse("$_",(Get-Culture))} | sort | ForEach-Object { $_.ToString('dd/mm/yyyy') }

Thanks Dave. That works. I just had to use “dd/MM/yyyy” in the place of “dd/mm/yyyy” in your code.

Ah, good catch. I always forget which is which. :slight_smile: