Jammer
Jammer

Reputation: 2420

Sorting an array of dates

I have created an array from a CSV of date values and now need to be able to sort them so that I can then get the latest date from the array.

I have tried:

Array.Sort()

but this doesn't sort correctly, I suppose because the array values are strings, any body got any ideas??

Thanks for any help.

CODE USED TO CREATE ARRAY

'array string exampel: "19/07/2012,23/07/2012,23/07/2012,19/07/2012,25/07/2012"
Dim ArrDates As Array = ArrDates .Split(",")

SOLUTION

Dim ArrAgentsReportCheck As Array = AgentsReportCheck.Split(",")

Dim ArrDates As New List(Of Date)
For i As Integer = 0 To ArrAgentsReportCheck.Length - 1
    ArrDates.Add(ArrAgentsReportCheck(i))
Next

ArrDates.Sort()
Dim LatestDate As Date = ArrDates.Max()

Upvotes: 0

Views: 5729

Answers (3)

dotNET
dotNET

Reputation: 35410

ArrDates = ArrDates.OrderBy(Function(d) DateTime.ParseExact(d, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)).ToArray()

Alternately, you can use OrderByDescending() depending upon your needs.

Upvotes: 3

Shaikh Farooque
Shaikh Farooque

Reputation: 2640

As astander said, It is very complicated to sort a array having datetime values. Instead just convert the array to List or ArrayList and make your life easy.

For ArrayList you can use the following syntax:

List<DateTime> dates = ... // init and fill
dates.Sort();
dates.Reverse();

Upvotes: 2

garf1eld
garf1eld

Reputation: 104

One way would be to convert strings to DateTime using DateTime.ParseExact

Another way just to write your own IComparer and pass to Array.Sort

Upvotes: 1

Related Questions