RSS

Tip of the day

07 Mar

Hi folks,

Here is the working code for comparing the dates using java Comparator Interface.

//Testing Class
public class TestDateCompare {
public static void main(String[] args) {
Map<String,String> unsortedMap = new HashMap<String,String>();
List list = new ArrayList();
unsortedMap.put(“1”, “05/30/2010 21:14:21”);
unsortedMap.put(“2”, “06/30/2012 21:14:20”);
unsortedMap.put(“3”, “05/14/2013 21:14:21”);
unsortedMap.put(“4”, “02/09/2012 21:14:21”);
unsortedMap.put(“5”, “11/04/2012 21:14:21”);
unsortedMap.put(“6”, “01/01/2014 02:27:33”);
unsortedMap.put(“7”, “05/11/2019 10:27:25”);
unsortedMap.put(“8”, “02/03/2014 03:52:46”);
unsortedMap.put(“9”, “05/04/2013 03:32:29”);
unsortedMap.put(“10”, “02/01/2010 02:27:33”);

list.add(unsortedMap.get(“1”));
list.add(unsortedMap.get(“2”));
list.add(unsortedMap.get(“3”));
list.add(unsortedMap.get(“4”));
list.add(unsortedMap.get(“5”));
list.add(unsortedMap.get(“6”));
list.add(unsortedMap.get(“7”));
list.add(unsortedMap.get(“8”));
list.add(unsortedMap.get(“9”));
list.add(unsortedMap.get(“10”));

Collections.sort(list, new DateCompareDemo());
System.out.println(“list –>> “+list); // Sorted result Here.
}
}

// Pulgin – Class
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
public class DateCompareDemo implements Comparator {
public int compare(Object o1, Object o2) {
Date finalDate1 = null;
Date finalDate2 = null;
String str1 = (String) o1;
String str2 = (String) o2;
String[] datetmstmp1 = str1.split(” “);
String[] datetmstmp2 = str2.split(” “);
String dateTimeStamp1 = datetmstmp1[0] + ” ” + datetmstmp1[1];
String dateTimeStamp2 = datetmstmp2[0] + ” ” + datetmstmp2[1];
SimpleDateFormat formatDate = new SimpleDateFormat(
“MM/dd/yyyy hh:mm:ss”);
try {
finalDate1 = formatDate.parse(dateTimeStamp1);
finalDate2 = formatDate.parse(dateTimeStamp2);
} catch (ParseException e) {
e.printStackTrace();
}
return finalDate2.compareTo(finalDate1);
}
}

Happy Coding!.

Get glued to know more updates.

Have a nice day:-)

 

Advertisements
 
Leave a comment

Posted by on March 7, 2013 in Uncategorized

 

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

 
%d bloggers like this: