Creating date ranges in JodaTime

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

I have two dates, first I need to create date ranges between these two dates and store them in an array. This is what I do.

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 get the problem.

 Type mismatch: cannot convert from DateTime to LocalDate > LocalDate listOfDates = > startDate.withFieldAdded(DurationFieldType.days(), i); > dates.add(listOfDates); } 
+7
source share
3 answers

Use org.joda.time.Interval

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

Doesn't work toLocalDate() ?

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

In any case, do you really need to create each date? If I really need it, I'll just do something similar to this:

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

I came here looking for this, but none of the 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)); } 

Keep in mind that LocalDates are immutable, so you don't actually change it when you call plusDays (...). Also note that I use <= to include the last day (in your example, this will be January 31st).

+2
source

All Articles