Convert java Date to chronologically sorted string?

I'm lazy, I know (hey, at least the next time I do this google, I will find the answer)

Do you have an existing code snippet that takes a Date object and generates a string that has a sort order equivalent to chronological order?

I want the string to contain all parts of the date (day, month, hour, minute, milliseconds, ...) and that when comparing two strings, the string representing the earliest date will be before the string representing the later date.

+4
source share
3 answers
Date[] dates=//....; List<String> listToSort=new ArrayList<String>(dates.length); SimpleDateFormat format=new SimpleDateFormat ("yyyyMMddHHmmssSSS"); for(Date date: dates) { String sDate=format.format(date); listToSort.add(sDate); } Collections.sort(listToSort); 

I am also lazy, so maybe it has some compilation errors or not (did not check it).

+6
source

  java.text.DateFormat dateFormat = new java.text.SimpleDateFormat ("yyyyMMddHHmmssSSSS");
 java.util.Date date = new java.util.Date ();
 // convert to GMT, if necessary, see this
 String sortableDate = dateForamt.format (date);
+2
source

ISO 8601 defines a set of standard representations of date and time that have the following property:

Date and time values ​​are organized from the most significant: year, month (or week), day, hour, minute, second and fraction of a second. Thus, the lexicographical order of presentation corresponds to the chronological order, with the exception of dates of presentation with negative years.

This means that any ISO 8601 format is right for you - sorting dates in ISO 8601 format in alphabetical order is equivalent to sorting them in chronological order.

You will not need to format dates in ISO 8601 format using DateFormat directly or the powerful Joda Time .

+1
source

All Articles