Convert String "2008-02-10T12:29:33.000" to a Date with the same format 2008-02-10T12:29:33.000 in Java

70 views Asked by At

I have an ArrayList that contains strings like 2008-02-10T12:29:33.000

[2008-02-11T12:29:33.000, 2008-02-10T12:29:33.000]...

I want to sort this ArrayList in natural order. For this I have to convert this strings into a Date I quess. The order after sorting sorting the ArrayList above shoult be:

[2008-02-10T12:29:33.000, 2008-02-11T12:29:33.000]

The programming language that I use is Java.

3

There are 3 answers

3
gtgaxiola On BEST ANSWER

I don't believe you need to do any conversion, as there is a natural order of those strings (at least I can't see a counterexample).

So Collections.sort() should do the trick.

3
assylias On

Although you could just sort the strings, I would store those dates as LocalDateTimes instead of strings and keep them that way. That will make manipulating them much easier.

The transformation could look like:

List<String> list = Arrays.asList("2008-02-11T12:29:33.000", "2008-02-10T12:29:33.000");
List<LocalDateTime> dates = list.stream().map(LocalDateTime::parse).collect(toList());

(this works because your strings are in proper ISO format).

And then sorting is as simple as:

Collections.sort(dates);
2
Mrunmaya On
ArrayList<String> dates = new ArrayList<String>();
dates.add("2008-02-11T12:29:33.000");
dates.add("2008-02-10T12:29:33.000");
Collections.sort(dates);
for (String date : dates)
{
  System.out.println(date);
}