Modgo
Modgo

Reputation: 77

how can i sort data by field stored string as Date format "yyyy/MM/dd HH:mm:ss"

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);
            }
        }
    }

}

Upvotes: 1

Views: 344

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

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

Upvotes: 2

Related Questions