Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of time strings in Java or Groovy

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.

like image 474
Vadym Kovalenko Avatar asked Nov 29 '22 02:11

Vadym Kovalenko


1 Answers

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

like image 88
tim_yates Avatar answered Dec 04 '22 17:12

tim_yates