简体   繁体   English

使用 joda 时间库比较日期字符串

[英]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.我有两个日期字符串,“2011-04-29”和“2011-01-28”,我想使用 Joda Time 比较它们。 Is there a way to do that?.有没有办法做到这一点?。 An example would be really appreciated.一个例子将不胜感激。

Thanks谢谢

First you need to parse them.首先,您需要解析它们。 Use DateTimeFormat :使用DateTimeFormat时间格式:

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

Then use DateTime.isBefore(..) to compare them:然后使用DateTime.isBefore(..)来比较它们:

if (dateTime1.isBefore(dateTime2))

Can also be used ltn4java the library as follows:也可以使用ltn4java的库如下:

    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 Library的下载页面是http://code.google.com/p/ltn4java/downloads/list

If your date strings are in format "yyyy-MM-dd" you can apply simple string comparison:如果您的日期字符串格式为“yyyy-MM-dd”,您可以应用简单的字符串比较:

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.如果 s1 在字典上比 s2 “大”,那么结果将为 TRUE,这就是您所需要的。 To get more info read javadoc for compareTo() method.要获取更多信息,请阅读 javadoc 以了解 compareTo() 方法。

In addition to @Bozho's answer we can use AbstractInterval.isAfter :除了@Bozho 的回答,我们还可以使用AbstractInterval.isAfter

if (dateTime2.isAfter(dateTime1))

Convert the strings to date objects and compare those.将字符串转换为日期对象并进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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