简体   繁体   中英

How to sort Date which is in string format in java?

I have an arraylist with string values like

ArrayList<String> datestring=new ArrayList<String>();
datestring.add("01/21/2013 @03:13 PM");
datestring.add("01/21/2013 @04:37 PM");
datestring.add("01/21/2013 @10:41 AM");
datestring.add("01/21/2013 @10:48 AM");
datestring.add("01/22/2013 @06:16 AM");
datestring.add("01/22/2013 @06:19 AM");
datestring.add("01/21/2013 @05:19 PM");
datestring.add("01/21/2013 @05:19 PM");

Can any body help me on sorting the above list? So that the values are sorted according to AM and PM format.
The expected output after sorting should be

for (String s : datestring)
{
    System.out.println(s);
}

.

01/21/2013 @10:41 AM;
01/21/2013 @10:48 AM;
01/21/2013 @03:13 PM;
01/21/2013 @04:37 PM;
01/21/2013 @05:16 PM;
01/21/2013 @05:19 PM;
01/22/2013 @06:16 AM;
01/22/2013 @06:19 AM;

try this

    Collections.sort(datestring, new Comparator<String>() {
        DateFormat f = new SimpleDateFormat("MM/dd/yyyy '@'hh:mm a");
        @Override
        public int compare(String o1, String o2) {
            try {
                return f.parse(o1).compareTo(f.parse(o2));
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
        }
    });

or with Java 8

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy '@'hh:mm a");
    Collections.sort(datestring, (s1, s2) -> LocalDateTime.parse(s1, formatter).
            compareTo(LocalDateTime.parse(s2, formatter)));

One can compare the List of date in string format by using the compareTo as given below.

ArrayList<String> datestring=new ArrayList<String>();
datestring.add("01/21/2013 @03:13 PM");
datestring.add("01/21/2013 @04:37 PM");
datestring.add("01/21/2013 @10:41 AM");
datestring.add("01/21/2013 @10:48 AM");
datestring.add("01/22/2013 @06:16 AM");
datestring.add("01/22/2013 @06:19 AM");
datestring.add("01/21/2013 @05:19 PM");
datestring.add("01/21/2013 @05:19 PM");

Collections.sort(datestring, new Comparator<String>() {
                @Override
                public int compare(String object1, String object2) {
                    return object1.compareTo(object2);
                }
            });

By using this you even dont have to parse the String into date

One option is to add the dates to a TreeMap, with the unformatted date as the key, and the formatted date as the value. Using a TreeMap will sort the values automatically.

private ArrayList<String> sortDates(ArrayList<String> dates) throws ParseException {
    SimpleDateFormat f = new SimpleDateFormat("dd MMM yyyy");
    Map <Date, String> dateFormatMap = new TreeMap<>();
    for (String date: dates)
        dateFormatMap.put(f.parse(date), date);
    return new ArrayList<>(dateFormatMap.values());
}

java.time

First, as bowmore has already said , you should not keep strings in your list. Instead, use instances of java.time classes.

Keep LocalDateTime objects. Or ZonedDateTime if you know in which time zone the times are. Strings are good for presentation to the user, not for manipulation in your program such as sorting.

The following code converts your list to a List<LocalDateTime> :

    DateTimeFormatter formatter 
            = DateTimeFormatter.ofPattern("MM/dd/uuuu '@'hh:mm a", Locale.ENGLISH);

    List<LocalDateTime> dateTimeList = datestring.stream()
            .map(ds -> LocalDateTime.parse(ds, formatter))
            .collect(Collectors.toCollection(ArrayList::new));

Now sorting is straightforward:

dateTimeList.sort(Comparator.naturalOrder());

LocalDateTime have a natural order since they implement Comparable , so Comparator.naturalOrder() is fine for sorting. Another way of obtaining the same sorting is:

dateTimeList.sort(LocalDateTime::compareTo);

To present the sorted data to the user we want to format the date-times into strings, of course:

dateTimeList.forEach(ldt -> System.out.println(ldt.format(formatter)));

The output is:

01/21/2013 @10:41 AM
01/21/2013 @10:48 AM
01/21/2013 @03:13 PM
01/21/2013 @04:37 PM
01/21/2013 @05:19 PM
01/21/2013 @05:19 PM
01/22/2013 @06:16 AM
01/22/2013 @06:19 AM

Except for the semicolons and a single simple typo I believe this is precisely what you asked for.

Link: Oracle tutorial: Date Time explaining how to use java.time , the modern Java date and time API that includes LocalDateTime and DateTimeFormatter .

While there is a technical way to get around your problem, the basic mistake is to represent Date s as String s, a form of 'primitive obsession'. If you have textual input, convert it to java.util.Date or an appropriate joda class ( LocalDateTime seems appropriate here). These classes implement Comparable out of the box, and sorting them is easy. But they also have all the other logic on board you're likely to need when manipulting date/time instances, Strings do not.

Update

Since java 8 I'd hihgly recommend using its LocalDateTime class instead.

ArrayList doesnt support sorting by default. You can use

public static <T> void sort(List<T> list, Comparator<? super T> c) from java.util.Collections class. pass your implementation of comparator to sort dates, something like

http://www.coderanch.com/t/392338/java/java/compare-Dates-String-Format

In Your class add this.

protected LocalDateTime getTrnDateLocalFormat() {

        LocalDateTime localDateTime = LocalDateTime.parse(this.yourDate.toLowerCase(), DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm:ss a"));
        return localDateTime;
    }

.sorted(Comparator.comparing(YourClass::getTrnDateLocalFormat)).collect(Collectors.toList());

Probably you can write a custom comparator to compare the Date Strings and order based on the requirement. Then you would be able to sort the collection with the implemented comparator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM