博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家,
👉​​​点击跳转到网站​

前言:
项目开发中,需要实现音频文件的下载,根据时间降序排列数据列表
步骤一:
创建时间工具类DateUtil

创建stringToDate()方法将字符串转换为date日期格式:

public static Date stringToDate(String dateString){
//从第一个字符开始解析
ParsePosition position = new ParsePosition(0);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateValue = simpleDateFormat.parse(dateString,position);
return dateValue;
}

分析:

1.ParsePosition 是 Format 及其子类所使用的简单类,用来在分析过程中跟踪当前位置。

2.对参数dateString(String类型)从第一个字符开始解析(由position ),转换成java.util.Date类型,
而这个Date的格式为"yyyy-MM-dd HH:mm:ss"
(因为SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);)

3.simpleDateFormat.parse():将字符串转换为Date日期格式
simpleDateFormat.format():将Date日期格式转换为字符串

步骤二:

在显示数据列表的Activity中通过比较器比较时间,之后提供适配器的对象

//通过比较器比较时间
Collections.sort(userDowns, new Comparator<UserDown>() {
@Override
public int compare(UserDown o1, UserDown o2) {
Date date1 = DateUtil.stringToDate(o1.DownTime);
Date date2 = DateUtil.stringToDate(o2.DownTime);
//按照降序排列,如果按升序排列用after即可
if (date1.before(date2)) {
return 1;
} else {
return -1;
}
}
});
//提供适配器的对象
mAdapter = new MyDownloadAdapter(this, userDowns);

分析按照降序排序的两种方法:
before() :如果date1<date2 返回正数,否则返回负数
after():如果date1>date2 返回负数, 否则返回正数

注:

public int compare(String o1, String o2) :比较其两个参数的顺序。

两个对象比较的结果有三种:大于,等于,小于。

如果要按照升序排序, 则o1 小于o2,返回(负数),相等返回0,o1大于o2返回(正数)

如果要按照降序排序, 则o1 小于o2,返回(正数),相等返回0,o1大于o2返回(负数)