0

I want to sort a list of strings which are formatted to be parsed to dateTime

for example :

19-06-2014
18-06-2014
17-06-2014

// all are strings

with this block of code :

var orderedList = newlist.OrderByDescending( x => DateTime.Parse(x)).ToList();

this gives me the following exception : String was not recognized as a valid DateTime.

As far as i know XX-XX-XXX is correct if you want to parse it to dateTime ?

1 Answers1

4

Use DateTime.ParseExact or TryParseExact as dd-MM-yyyy is not a standard date format in most Cultures (where it's usually dd/MM/yyyy or MM/dd/yyyy).

IEnumerable<DateTime> dtes =
    datesAsString.Select(
        str => DateTime.ParseExact( str, "dd-MM-yyyy", CultureInfo.InvariantCulture )
    ).
    OrderByDescending( dt = > dt );
Dai
  • 141,631
  • 28
  • 261
  • 374
  • Or `yyyy-MM-dd` for a machine-readable standard format... – Jon Skeet Oct 14 '14 at 17:41
  • 1
    @JonSkeet the OP didn't say he was responsible for the format of his strings, otherwise I'd have set to dump an int64 of unix time ;) – Dai Oct 14 '14 at 17:43
  • @Dai I think Jon's point is that `yyyy-mm-dd` is still human-readable and unambiguous because no cultures use a `yyyy-dd-mm` format. – D Stanley Oct 14 '14 at 17:48