简体   繁体   中英

Comparing date strings using joda time library

I have two date strings say, "2011-04-29" and "2011-01-28", and i want to compare them using Joda Time. Is there a way to do that?. An example would be really appreciated.

Thanks

First you need to parse 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))

Can also be used ltn4java the library as follows:

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

The download page of the Library is http://code.google.com/p/ltn4java/downloads/list

If your date strings are in format "yyyy-MM-dd" you can apply 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 "bigger" than s2 and that's what you need. To get more info read javadoc for compareTo() method.

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

if (dateTime2.isAfter(dateTime1))

Convert the strings to date objects and compare those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM