public class MainActivity extends Activity {
private ListView mListView = null;
private List<TestDate> mList = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) this.findViewById(R.id.main_listView);
mList = new ArrayList<TestDate>();
initData();
Collections.sort(mList, new Comparator<TestDate>() {
/**
*
* @param lhs
* @param rhs
* @return an integer < 0 if lhs is less than rhs, 0 if they are
* equal, and > 0 if lhs is greater than rhs,比较数据大小时,这里比的是时间
*/
@Override
public int compare(TestDate lhs, TestDate rhs) {
Date date1 = DateUtil.stringToDate(lhs.getDate());
Date date2 = DateUtil.stringToDate(rhs.getDate());
// 对日期字段进行升序,如果欲降序可采用after方法
if (date1.before(date2)) {
return 1;
}
return -1;
}
});
mListView.setAdapter(new MyAdapter(this, mList));
}
private void initData() {
mList.add(new TestDate("2012-12-12 12:30", "zhangsan"));
mList.add(new TestDate("2012-12-12 10:20", "lisi"));
mList.add(new TestDate("2012-12-11 10:21", "lisi"));
mList.add(new TestDate("2012-12-11 10:20", "lisi"));
mList.add(new TestDate("2012-12-13 01:03", "wangwu"));
mList.add(new TestDate("2012-12-10 02:04", "zhaoliu"));
mList.add(new TestDate("2012-12-15 23:00", "tianqi"));
mList.add(new TestDate("2012-11-12 22:30", "wangwu"));
mList.add(new TestDate("2012-12-17 08:24", "shimei"));
mList.add(new TestDate("2012-11-10 11:10", "shisanmei"));
mList.add(new TestDate("2012-12-18 16:50", "wangan"));
mList.add(new TestDate("2012-12-19 18:00", "wangjiu"));
mList.add(new TestDate("2012-12-20 19:30", "wusi"));
mList.add(new TestDate("2012-12-20 19:30", "wusi"));
}
}
public class DateUtil {
public static Date stringToDate(String dateString) {
ParsePosition position = new ParsePosition(0);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date dateValue = simpleDateFormat.parse(dateString, position);
return dateValue;
}
}