Sort date with Timezone format using Joda Time

Here’s a sample Java code on how to sort dates form Strings to Date objects in a “Complete date plus hours and minutes with “T” / Timezone” format [ YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00) ]. The format standards are taken here > http://www.w3.org/TR/NOTE-datetime

The sample code uses Joda Time [ http://www.joda.org/joda-time/ ] . But Java 8 already has libraries that have the same capabilities as Joda Time. But as for Java 7 and below, Joda Time is much recommended.


//import Joda Time libraries
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;

//Sample Snippet Code below
//The objective of the code is to parse the date from 
//Strings and convert it to DateTime ( Joda Time ). 
//Place all the DateTime objects in a List, then sort 
//the DateTime using Collections.sort()

DateTime date = DateTime.parse("2014-06-18T06:26:56-07:00");
DateTime date1 = DateTime.parse("2013-12-28T14:11:12-08:00");
DateTime date2 = DateTime.parse("2013-11-28T14:11:12-08:00");
DateTime date3 = DateTime.parse("2011-11-28T14:11:12-08:00");
		
		
List<DateTime> dateList = new ArrayList<DateTime>();
		
dateList.add(date);
dateList.add(date1);
dateList.add(date2);
dateList.add(date3);
		
Collections.sort(dateList);
		
for(DateTime d : dateList){
	System.out.println(d.toString());
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s