晚灯下的烟火 2016-09-06 02:28 采纳率: 0%
浏览 1815
已采纳

arraylist<String>排序问题

内容:
app开锁成功
Time:16年09月05日 15时58分46秒

app开箱失败
Time:16年09月05日 15时59分45秒

app开锁成功
Time:16年09月05日 15时57分40秒
这样的数据怎么进行根据年月日时分秒进行排序?

  • 写回答

6条回答 默认 最新

  • 普通网友 2016-09-06 03:10
    关注

    如果你说的是List中一条数据就是 “app开锁成功\nTime:16年09月05日 15时57分40秒”,
    那么可以使用正则表达式匹配并提取时间,然后通过SimpleFormatDate将其转换为Calendar对象,
    通过Calendar对象的before和after函数可以比较两个日期的先后。

    1. 通过正则表达式提取时间(嫌麻烦你就直接截取):
    String str="app开锁成功\nTime:16年09月05日 15时57分40秒";
    Pattern pattern=Pattern.compile("(?<=Time:).+");
    Matcher matcher=pattern.matcher(str);
    if(matcher.find()){
    System.out.println("提取的时间为:\t"+matcher.group());
    }
    

    将时间字符串转换为Calendar对象并比较时间先后:

    String date = matcher.group();
    //紧接前面的提取代码,这里的代码都是demo
    System.out.println("提取的时间为:\t" + date);
    
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy年MM月dd日 HH时mm分ss秒", Locale.getDefault());
    try {
         Date da = simpleDateFormat.parse(date);
         Calendar calendar = Calendar.getInstance();
         calendar.setTime(da);
    
         Calendar another = Calendar.getInstance();
         if (another.after(calendar)) {
               System.out.println("今天(" + simpleDateFormat.format(another.getTime()) + ")在" + simpleDateFormat.format(calendar.getTime()) + "之后");
         } else {
               System.out.println("今天(" + simpleDateFormat.format(another.getTime()) + ")在" + simpleDateFormat.format(calendar.getTime()) + "之前");
         }
     } catch (ParseException e) {
            e.printStackTrace();
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码