如何对Java或Groovy中的时间字符串列表进行排序 [英] How to sort a list of time strings in Java or Groovy

查看:382
本文介绍了如何对Java或Groovy中的时间字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串列表,每个字符串都包含这样的时间:


03:00 AM,12:30 PM,16:15


我需要按顺序对它们进行排序:先放上am次并比较小时,而不是只是字符串中的第一个数字。

解决方案

这个适用于groovy, b

 列表日期= [16:15,12:30 PM,07:00,03:00 AM] 

dates.sort {d - >
['h:mm a','H:mm'] .findResult {fmt - >
尝试{
Date.parse(fmt,d).time
} catch(e){}
}
}

它基本上是用AM / PM来尝试,然后在没有它的情况下尝试,如果失败的话

I have a list of strings, each one contains time like this:

"03:00 AM", "12:30 PM", "16:15"

I need to sort them in order: put "am" times first and compare hours, not just first digits in a string.

解决方案

This works for groovy, with all cases you gave:

List dates = [ "16:15", "12:30 PM", "07:00", "03:00 AM" ]

dates.sort { d ->
  [ 'h:mm a', 'H:mm' ].findResult { fmt ->
    try {
      Date.parse( fmt, d ).time
    } catch( e ) {}
  }
}

It basically tries with AM/PM and then tries without it if that fails

这篇关于如何对Java或Groovy中的时间字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆