Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert java Date to a chronologically sortable string?

Tags:

java

date

I'm lazy, I know (by hey, at least next time I Google it then I'll find the answer)

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

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

like image 955
ripper234 Avatar asked Dec 21 '22 21:12

ripper234


2 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'm lazy too, so maybe it has some compile errors, or not (haven't checked it).

like image 169
Tomas Narros Avatar answered Dec 24 '22 10:12

Tomas Narros


java.text.DateFormat dateFormat = 
    new java.text.SimpleDateFormat("yyyyMMddHHmmssSSSS");
java.util.Date date = new java.util.Date();
// convert to GMT, if needed, look at this
String sortableDate = dateForamt.format(date);
like image 21
khachik Avatar answered Dec 24 '22 09:12

khachik