I have an array of string folder names, each of which include a date, time, and timezone. The array is as so:
[
"folder_name_01-18-2020-19_00_00_PM_EST",
"folder_name_05-01-2019-00_00_00_AM_EDT",
"folder_name_12-15-2019-02_00_00_AM_EST"
]
How can I sort this array so that all the folder names are sorted in ascending order by their date (earliest to latest), eg. the result of the above array should be this:
[
"folder_name_05-01-2019-00_00_00_AM_EDT",
"folder_name_12-15-2019-02_00_00_AM_EST",
"folder_name_01-18-2020-19_00_00_PM_EST"
]
The folder name strings are guarenteed to be in this exact format. folder_name
never changes, so only the time stamp will change for each folder name.
I've thought of a high level solution that sounds very inefficient:
Isolate the datetime from the folder name
Map the datetime to full folder name: {"05-01-2019-00_00_00_AM_EDT":"folder_name_05-01-2019-00_00_00_AM_EDT"}
Add the isolated datetime to an array
Sort the array of datetimes // potential trouble spot b/c of the date format
result = new array()
For item in sorted array:
result.add(map.get(item))
return result
I'm wondering if improvements and/or better methods could be used to solve this problem
Figured out a much better solution using a custom Comparator
: Grab the date time using the substring()
function, parse it with SimpleDateTime
, grab the epoch time from the resulting Date
objects and then use Long.compare()
to determine which time is later.