tl;dr
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 )
)
)
)
java.time
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 )
About java.time
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?