Since you mention in your question that you already have an ArrayList
of Strings
, and you show that the strings are all dates that are already formatted in ISO8601, your task is very simple: just sort the arraylist as-is.
That is one of the many benefits of ISO8601!
From Wikipedia:
Date and time values are organized from the most to the least significant: year, month (or week), day, hour, minute, second, and fraction of second. The lexicographical order of the representation thus corresponds to chronological order, except for date representations involving negative years. This allows dates to be naturally sorted by, for example, file systems.
In more detail:
List<String> dateStrings = Arrays.asList(
"2011-07-18T10:39:31.855Z",
"2012-09-18T10:19:31.855Z",
"2011-07-18T10:39:31.055Z",
"1903-12-01T00:39:31Z",
);
Arrays.sort(dateStrings);
// now dateStrings is sorted by date.
Again the idea here is that you do not have to convert the strings to dates to do the sort.
As an aside, if your list contained actual Date
objects, you can also just call Arrays.sort
and your list would get sorted properly as well, because dates are comparable in Java. But your question asked about strings, and strings in ISO8601 at that, so if this was an important part of your problem you might as well take advantage of that benefit of the format. TL;DR you don't need a dateformat to sort.