我如何通过按日期格式"yyyy/MM/dd HH:mm:ss"存储的字段对数据进行排序? [英] how can i sort data by field stored string as Date format "yyyy/MM/dd HH:mm:ss"

查看:318
本文介绍了我如何通过按日期格式"yyyy/MM/dd HH:mm:ss"存储的字段对数据进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以"yyyy/MM/dd HH:mm:ss"之类的日期格式存储的数据字段.我想使用orderby按日期对数据进行排序,但是我该怎么做

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

}

推荐答案

正如道格·史蒂文森(Doug Stevenson)所述,您最好将日期存储为String.最好的选择是将日期转换为格林尼治标准时间1970年1月1日00:00:00以来的毫秒数

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

在Java中,这是通过这种方式完成的

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

或Java 8以下版本

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

这篇关于我如何通过按日期格式"yyyy/MM/dd HH:mm:ss"存储的字段对数据进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆