Android json数据按时间排序

it2022-05-05  112

好久没写博客了.今天搞一下

实现json数据按时间排序只需要你粘贴复制

首先我们先搞点json数据

private void time() { /** * 方便大家看懂 多new几个JSONObject */ ArrayList<String> time_arr = new ArrayList(); JSONObject jsonObject1 = new JSONObject(); JSONObject jsonObject2 = new JSONObject(); JSONObject jsonObject3 = new JSONObject(); JSONObject jsonObject4 = new JSONObject(); try { jsonObject1.put("time", "2018-7-18 17:02"); jsonObject2.put("time", "2017-7-18 17:03"); jsonObject3.put("time", "2019-7-18 17:04"); jsonObject4.put("time", "2019-7-18 17:05"); time_arr.add(jsonObject1.toString()); time_arr.add(jsonObject2.toString()); time_arr.add(jsonObject3.toString()); time_arr.add(jsonObject4.toString()); } catch (JSONException e) { e.printStackTrace(); } /** * 排序前 time_arr数据 *[{"time":"2018-7-18 17:02"}, {"time":"2017-7-18 17:03"}, {"time":"2019-7-18 17:04"}, {"time":"2019-7-18 17:05"}] */ time_sorting_List(time_arr); /** * 排序后 time_arr数据 *[{"time":"2019-7-18 17:05"}, {"time":"2019-7-18 17:04"}, {"time":"2018-7-18 17:02"}, {"time":"2017-7-18 17:03"}] */ }

下面是排序方法:

@SuppressLint("SimpleDateFormat") private List<String> time_sorting_List(List<String> time) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date d1; Date d2; String temp_r = ""; //做一个冒泡排序,大的在数组的前列 for (int i = 0; i < time.size() - 1; i++) { for (int j = i + 1; j < time.size(); j++) { ParsePosition pos1 = new ParsePosition(0); ParsePosition pos2 = new ParsePosition(0); String timei = ""; try { JSONObject jsonObject1 = new JSONObject(time.get(i)); timei = jsonObject1.getString("time"); } catch (JSONException e) { } String timej = ""; try { JSONObject jsonObject1 = new JSONObject(time.get(j)); timej = jsonObject1.getString("time"); } catch (JSONException e) { } d1 = sdf.parse(timei, pos1); d2 = sdf.parse(timej, pos2); if (d1.before(d2)) {//如果队前日期靠前,调换顺序 temp_r = time.get(i); time.set(i, time.get(j)); time.set(j, temp_r); } } } return time; }


最新回复(0)