在Java中按日期排序时间戳

时间:2012-11-24 22:26:55

标签: android timestamp

我的课程Event包含许多不同的变量,例如名称说明开始时间结束时间,然后我的Day课程具有可变日期和ArrayList这些Events。现在我想要Days的ArrayList,并且每个Day应包含同一天的Events。默认情况下,我获取事件列表,我需要根据此列表创建日期。所有时间都是 int unix timestamp格式。

示例澄清我的目的:

Day 25.11
Event1
Event2
Event3

Day 26.11
Event1

Day 27.11
Event1
Event2
Event3
Event4

我尝试的代码没有工作结果:

private void getObjects(String url) throws JSONException, Exception {
    JSONObject jsonObject = new JSONObject(new NetTask().execute(url).get());
        JSONArray job1 = jsonObject.getJSONArray("events");
        ArrayList<Event> events = new ArrayList<Event>();
        Calendar calPrev = Calendar.getInstance();
        boolean first = true;
        for (int i = 0; i < job1.length(); i++) {
            JSONObject myEventArray = job1.getJSONObject(i);
            int start = myEventArray.getInt("start");
            int end = myEventArray.getInt("end");
            String name = myEventArray.getString("name");
            String description = myEventArray.getString("description");

            if(first){
                calPrev.setTimeInMillis(start*1000L);
                events.add(new Event(start,end,name,description));
                first = false;
            }else{
                Calendar calCur = Calendar.getInstance();
                calCur.setTimeInMillis(start*1000L);

                if(calPrev.get(Calendar.YEAR) == calCur.get(Calendar.YEAR) && calPrev.get(Calendar.DAY_OF_YEAR) == calCur.get(Calendar.DAY_OF_YEAR)){
                    events.add(new Event(start,end,name,description));
                }else{
                    days.add(new Day(323,events)); // HERE I CREATE NEW DAY AND ADD IT TO ARRAY
                    events.clear();
                    events.add(new Event(start,end,name,description));
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以使用此方法获取唯一日期,然后将每天的事件添加到哈希映射private HashMap<Integer, ArrayList<YourModel>> eventInfo = new HashMap<Integer, ArrayList<YourModel>>();中:

private List<String> getUniqueDays(List<YourModel> list)
{
    Set<String> res = new LinkedHashSet<String>();

    for (int i = 0; i < list.size(); i++)
    {
        if (list.get(i).getDay().length() > 0)
            res.add(list.get(i).getDay());
    }

    List<String> temp = new ArrayList<String>(res);
    Collections.sort(temp, dateComparator);
    return temp;
}

Comparator<String> dateComparator = new Comparator<String>()
{
    @Override
    public int compare(String lhs, String rhs)
    {
        try
        {
            DateFormat format = new SimpleDateFormat("MM-dd-yyyy h:mm:ss a");
            return format.parse(lhs).compareTo(format.parse(rhs));
        }
        catch (Exception e)
        {
            return 0;
        }
    }
};