1

i have data field stored in date format like "yyyy/MM/dd HH:mm:ss" .i want to sort data by date using orderby ,but how can i do that

i do that by code but it is take long time when it work on a huge number of it

public void sortBy_Desc(String SortBy) {

    int size = universityData.size();
    int after;

    for (int m = size; m >= 0; m--) {
        for (int before = 0; before < size - 1; before++) {
            after = before + 1;

            long first = 0, second = 0;

            if (SortBy.equals(Data.EXAM_DATE)) {
                first = convertStringToDate(examData.get(before).getExam_date()).getTime();
                second = convertStringToDate(examData.get(after).getExam_date()).getTime();
            }
            else if (SortBy.equals(Data.REG_DATE)) {
                first = convertStringToDate(examData.get(before).getReg_end_date()).getTime();
                second = convertStringToDate(examData.get(after).getReg_end_date()).getTime();
            }
            else if (SortBy.equals(Data.FEE)) {
                String fee = getCurrencyType(examData.get(before).getExam_fee()).get(0);
                first = Integer.parseInt(fee);

                fee = getCurrencyType(examData.get(after).getExam_fee()).get(0);
                second = Integer.parseInt(fee);
            }

            if (first < second) {
                swapData(before, after);
            }
        }
    }

}
Modgo
  • 77
  • 2
  • 8

1 Answers1

2

As Doug Stevenson mentionned you should better store your dates as String. the best option is to convert your date to the number of milliseconds since January 1, 1970, 00:00:00 GMT

In Java, this is done this way

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millisSinceEpoch = date.getTime();

or the following with Java 8

long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
        .atOffset(ZoneOffset.UTC)
        .toInstant()
        .toEpochMilli();

It will then be easy to orderBy. If you want to get the reverse order (i.e. the most recent dates first) you can store

0 - millisSinceEpoch
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • 1
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Mar 20 '18 at 19:12