Putting simply, I have a string array of different dates and times. Each element is of this format:
2015-08-27T22:24:31.903
That is, YYYY-MM-DDTHH:MM:SS.MMM
I'm sorting them. Is there a default method available to sort this format?
What I'm doing now is splitting the string at T, converting the date and time to respective timestamps, adding them and then sorting the timestamp values. Is there a direct parser for this format available? A better solution is most-welcome.
Yes. Since the ISO string has date fields in descending order of magnitude, and fields are fixed-width, you can simple sort the strings directly using
Arrays.sort(Object[] a)
: Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.Yes.
LocalDateTime.parse(CharSequence text)
: Obtains an instance ofLocalDateTime
from a text string such as2007-12-03T10:15:30
.I take it those are strings. If you don't want to do the obvious (convert them to
java.util.Date
orjava.time.Instant
and compare the result), you can just compare them as strings, that particular datetime format (a nearly-full ISO-8601 timestamp, just missing a timezone indicator) works correctly when you use string comparison.Gratuitous example (live copy):
Output:
You can, of course, provide a
Comparator
if you need a different ordering (such as reverse order).1) Parse your strings using the appropriate SimpleDateFormat:
2) Store each date in a list. To do that firstly instantiate a new list...
... after the parse command add each date to the list:
3) Sort them using:
or