Comparing date strings using joda time library

I have two date strings: "2011-04-29" and "2011-01-28", and I want to compare them using Joda Time. Is there any way to do this ?. An example would be truly appreciated.

thanks

+7
source share
5 answers

First you need to analyze them. Use DateTimeFormat :

 DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime dateTime1 = fmt.parseDateTime(string1); 

Then use DateTime.isBefore(..) to compare them:

 if (dateTime1.isBefore(dateTime2)) 
+7
source

You can also use the ltn4java library as follows:

  DataCompare dc = new DataCompare(); int Resultado; Resultado = dc.compareWithTwoDatesString("2011-04-29","2011-01-28","yyyy-MM-dd"); 

Library download page http://code.google.com/p/ltn4java/downloads/list

+3
source

If the date strings are in the format "yyyy-MM-dd", you can apply a simple string comparison:

 String s1 = new String("2012-01-27"); String s2 = new String("2011-01-28"); System.out.println(s1.compareTo(s2)); 

The result will be TRUE if s1 is lexicographically β€œgreater” than s2, and what you need. For more information, read javadoc for the compareTo () method.

+2
source

Convert objects to a date and compare them.

0
source

In addition to @ Bozho's answer, we can use AbstractInterval.isAfter

 if (dateTime2.isAfter(dateTime1)) 
0
source

All Articles