开发者

Convert java Date to a chronologically sortable string?

开发者 https://www.devze.com 2023-01-23 06:01 出处:网络
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 objec开发者_开发百科t, and generates a string, that has a

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 objec开发者_开发百科t, 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.


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).


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);


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

Date and time values are organized from the most to the least significant: year, month (or week), day, hour, minute, second, and fraction of second. The lexicographical order of the representation thus corresponds to chronological order, except for date representations involving negative years.

This means that any ISO 8601 format would be OK for you -- sorting ISO 8601 formatted dates alphabetically is equivalent to sorting them chronologically.

It should not be difficult to format dates in ISO 8601 format, either using DateFormat directly, or the powerful Joda Time library.

0

精彩评论

暂无评论...
验证码 换一张
取 消