Generate Date ranges in JodaTime

江枫思渺然 提交于 2019-12-06 00:00:34

问题


I need to check if a date(in string) exists in array list.

I have two dates, first i need to generate date ranges between these two dates and store them in an Array. This is what I am doing.

DateTimeFormatter dateFromatter= DateTimeFormat.forPattern("MM/dd/yyyy");

DateTime startDate= formatter.parseDateTime("01/02/2012");
DateTime endDate= formatter.parseDateTime("01/31/2012");

 List<LocalDate> dates = new ArrayList<LocalDate>();


  int days = Days.daysBetween(startDate, endDate).getDays();
  for (int i=0; i < days; i++) {

This is where i am getting problem.

Type mismatch: cannot convert from DateTime to LocalDate

>   LocalDate listOfDates =
> startDate.withFieldAdded(DurationFieldType.days(), i);
> dates.add(listOfDates);

  }

回答1:


Use org.joda.time.Interval

Interval interval = new Interval(startDate, endDate);  
for (LocalDate date : dates)  
{   
  if (interval.contains(date))  
   // 



回答2:


Doesn't toLocalDate() work?

LocalDate listOfDates = 
    startDate.withFieldAdded(DurationFieldType.days(), i).toLocalDate();

Anyway, do you really need to generate each date? Unless I really need to, I would just do something similar to this:

Interval interval = new Interval(startDate.withTimeAsStartOfDay(), 
                                 endDate.withTimeAsStartOfDay().plusDays(1));
boolean isInInterval = interval.contains(date.withTimeAsStartOfDay());



回答3:


I came here looking for this, but neither solutions were acceptable to me - I ended up with the following:

int days = Days.daysBetween(startDate, endDate).getDays();

for(int i = 0; i <= days; i++) {
    dates.add(startDate.plusDays(i));
}

Bear in mind that LocalDates are immutable so you're not actually changing it when you call plusDays(...). Also notice that I use <= to include the final day (in your example this would be 31st January).



来源:https://stackoverflow.com/questions/9313151/generate-date-ranges-in-jodatime

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