如何比较创建为JodaTime LocalDate和LocalDateTime的两个日期?

时间:2014-03-13 10:41:52

标签: java jodatime

LocalDate startDate = new LocalDate(2014,1,2);

LocalDateTime startDateTime = new LocalDateTime(2014,1,2,14,0);

我需要将startDatestartDateTime与日期进行比较,如下所示:

// boolean equalDates = startDate.isequal(startDateTime.getDate());

是否可以这样做?

3 个答案:

答案 0 :(得分:11)

如果您只想比较日期部分,可以这样做:

LocalDate startDate = new LocalDate(2014, 1, 2);
LocalDateTime startDateTime = new LocalDateTime(2014, 1, 2, 14, 0);
LocalDate forCompare = startDateTime.toLocalDate();
System.out.println("equal dates: " + forCompare.equals(startDate));
// equal dates: true

docs

答案 1 :(得分:4)

LocalDate startDate = new LocalDate(2014,1,2);

LocalDateTime startDateTime = new LocalDateTime(2014,1,2,00,0);

System.out.println(startDate.toDate());
System.out.println(startDateTime.toDate());


if(startDate.toDate().compareTo((startDateTime.toDate()))==0){
 System.out.println("equal");       
}

输出将是:

Thu Jan 02 00:00:00 IST 2014

Thu Jan 02 00:00:00 IST 2014

等于

答案 2 :(得分:1)

如果你想检查一个日期是否介于另一个时间范围之间,比如date1之间的date2 4小时,joda只有你可以使用的场景有不同的类:

Hours h = Hours.hoursBetween(date1, date2);
Days s = Days.daysBetween(date1, date2);
Months m = Months.monthsBetween(date1,date2);

http://joda-time.sourceforge.net/apidocs/org/joda/time/base/BaseSingleFieldPeriod.html