How to compare two dates created as JodaTime LocalDate and LocalDateTime?

假装没事ソ 提交于 2019-12-22 05:35:33

问题


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

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

I need to compare startDate and startDateTime with respect to the date, something like this:

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

Is it possible to do this?


回答1:


If you just want to compare the date part, you can do it like so:

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




回答2:


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");       
}

the output will be:

Thu Jan 02 00:00:00 IST 2014

Thu Jan 02 00:00:00 IST 2014

equal




回答3:


If you want to check if say one date is in between another time frame, say is date1 4hrs in between date2, joda has different classes just for those scenarios you can use:

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



来源:https://stackoverflow.com/questions/22376022/how-to-compare-two-dates-created-as-jodatime-localdate-and-localdatetime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!