java Android - 如何按日期对arrayList 进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45049402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:28:49  来源:igfitidea点击:

Android - How to sort arrayList by date?

javaandroidsortingarraylist

提问by arsenallavigne

I'm trying to sort my arrayListby date. I stored the date on Firebase each time I receive a notification and is retrieved from there. I'm using Collections.sortbut I don't know how to implement onto my codes as my date format starts with a number in a string format like "12 Jul 2017 at 12:00am".

我正在尝试arrayList按日期对我的进行排序。每次收到通知并从那里检索时,我都会将日期存储在 Firebase 上。我正在使用,Collections.sort但我不知道如何在我的代码中实现,因为我的日期格式以字符串格式的数字开头,例如“2017 年 7 月 12 日上午 12:00”。

I've seen some examples of this on stackoverflow but I don't know how to make it work in my case. I will post screenshots and my codes below.

我在 stackoverflow 上看到了一些这样的例子,但我不知道如何让它在我的情况下工作。我将在下面发布屏幕截图和我的代码。

The dates are not sorted.

日期未排序。

enter image description here

在此处输入图片说明

NotificationFragment.java

通知片段.java

public class NotificationFragment extends Fragment {
        prepareNotification1();
        sortDate();
        return v;
    }

       private void prepareNotification1() {
            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            String userID = user.getUid();

  mRef.child("customers").child(userID).child("Notification").addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    Notification menu = dataSnapshot.getValue(Notification.class);
                    notificationList.add(menu);
                mAdapter.notifyDataSetChanged();
            }
 });
    }

    public void sortDate() {
        Collections.sort(notificationList, new Comparator<Notification>() {
            @Override
            public int compare(Notification lhs, Notification rhs) {
                return lhs.getDate().compareTo(rhs.getDate());
            }
        });
        mAdapter = new NotificationAdapter(getContext(), notificationList);
        mRecyclerView.setAdapter(mAdapter);
    }
}

MyFirebaseMessagingService.java

MyFirebaseMessagingService.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Calendar cal = Calendar.getInstance();

        String currentDateTimeString = DateFormat.getDateInstance().format(new Date());

        SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
        String currentTime = df.format(cal.getTime());

        String notificationTime = currentDateTimeString + " at " + currentTime;

        Notification newNotification = new Notification(remoteMessage.getData().get("body"), notificationTime);
        mRef.child("customers").child(userID).child("Notification").push().setValue(newNotification);
}

Notification.java

通知.java

public class Notification {
    private String message;
    private String date;


    public Notification(){
    }

    public Notification(String message, String date){
        this.message = message;
        this.date = date;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

回答by SpaceBison

Consider storing the date in Notificationas a long(unix time) or a Date(LocalDateTimeif you're using Java 8 support) and formatting it as a String only when displaying it to the UI.

考虑将日期存储Notificationlong(unix 时间) 或Date(LocalDateTime如果您使用 Java 8 支持) 并仅在将其显示到 UI 时将其格式化为字符串。

回答by Ritesh

Do sorting after parsing the date.

解析日期后进行排序。

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

If your date is in some other format, write the DateFormataccordingly.

如果您的日期采用其他格式,请相应地编写DateFormat

回答by Artem Samokhin

As I understand, Notification.getDate() returns String value. So, use

据我了解, Notification.getDate() 返回 String 值。所以,使用

public static Date toDate(String value) throws ParseException {
    DateFormat format = new SimpleDateFormat("d MMMM yyyy 'at' HH:mm'am'", Locale.ENGLISH);
    return format.parse(value);
}

this method to det Date from your String. Just get two dates and use Date.compareTo method.

此方法从您的字符串中检测日期。只需获取两个日期并使用 Date.compareTo 方法。

date1 = toDate(lhs.getDate());
date2 = toDate(rhs.getDate());
date1.compareTo(date2);

回答by Usman Rana

Instead of setting date like following in Notification model.

而不是在通知模型中设置日期如下。

String notificationTime = currentDateTimeString + " at " + currentTime;

String notificationTime = currentDateTimeString + " at " + currentTime;

you can save time as System.currentTimeinMillis();and while displaying then parse it to Date as following

你可以节省时间System.currentTimeinMillis(); 并在显示时将其解析为 Date 如下

DateFormat f = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
f.parse(timeStamp);