I am in a need of function, user defined, which could sort the dates from current time to old time.
I'm having list of 10 dates which I want to sort these dates starting from last recent date.
Currently I have a logic, in which if we can covert the date in milli-second then comparing it with current-milli-seconds and the least milli-second will be the recent date. That is,
CURRENT_MILLI_SECOND - A_DATE_CONVERTED_TO_MILLI_SECONDS = MILLI-SECONDS
Please suggest me if anyone can help me in this logic or any other logics...!!!
This is the formate which I am getting from server:
Thu Dec 27 11:02:43 GMT+05:30 2012
You can go with Comparator and can sort data by using compare()
Collections.sort(dateList, new Comparator<Date>(){
public int compare(Date date1, Date date2){
return date1.after(date2);
}
});
Try this:
Comparator date_comparator = new Comparator() {
@Override
public int compare(Date date1, Date date2){
return date1.compareTo(date2);
}
};
You can use Calendar
or Date
class to do so. Using calendar and Date you can compare two dates like date1.compare(date2) or date.before(date2) or date1.after(date2) such api's are available for your cases.
Collections.reverse(
new ArrayList<>().add(
OffsetDateTime.parse(
"Thu Dec 27 11:02:43 GMT+05:30 2012" ,
DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss OOOO uuuu" , Locale.US )
)
)
)
The modern approach uses java.time classes.
Define a formatting pattern to match. By the way, this is a terrible format; if you have any control, use standard ISO 8601 formats instead.
String input = "Thu Dec 27 11:02:43 GMT+05:30 2012" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss OOOO uuuu" , Locale.US );
Your input strings specify an offset-from-UTC but not a full time zone. So we parse as an OffsetDateTime
.
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2012-12-27T11:02:43+05:30
OffsetDateTime
objects already know how to sort themselves, as they implement Comparable
.
List< OffsetDateTime > odts = new ArrayList<>( 3 ) ;
odts.add( odt ) ;
odts.add( odt.plusMinutes( 7 ) ) ;
odts.add( odt.minusMinutes( 21 ) ) ;
Collections.sort( odts ) ;
You want the most recent at top of the list, so sort in reverse order.
Collections.reverse( odts ) ; // Reverse-order.
To compare individual java.time objects, call the isBefore
, isAfter
, and isEqual
/equals
methods.
thisOdt.isBefore( thatOdt )
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With