Java tutorial
/** * Copyright (c) 2011 Wolox <http://www.wolox.com.ar/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ar.com.wolox.commons.base.datetime; import java.util.Iterator; import java.util.NoSuchElementException; import javax.validation.constraints.NotNull; import org.joda.time.LocalDate; /** * Provides an abstraction to construct a {@LocalDate} range. * * * @author Luciano Zemin * @since 30/10/2011 */ public final class LocalDateRange implements Iterable<LocalDate> { private final LocalDate start; private final LocalDate end; /** * Creates the LocalDateRangeProvider. * * @param start * @param end */ public LocalDateRange(@NotNull final LocalDate start, @NotNull final LocalDate end) { if (start == null) { throw new IllegalArgumentException("start cannot be null"); } if (end == null) { throw new IllegalArgumentException("end cannot be null"); } if (start.isAfter(end)) { throw new IllegalArgumentException("start date must be before or equal to end date"); } this.start = start; this.end = end; } @Override public Iterator<LocalDate> iterator() { return new LocalDateRangeIterator(start, end); } /** * * Private class providing an iterator for {@LocalDateRange} * * * @author Luciano Zemin * @since 30/10/2011 */ private static final class LocalDateRangeIterator implements Iterator<LocalDate> { private LocalDate current; private final LocalDate end; /** * * Creates the LocalDateRangeIterator. * * @param start * @param end */ private LocalDateRangeIterator(@NotNull final LocalDate start, @NotNull final LocalDate end) { if (start == null) { throw new IllegalArgumentException("start cannot be null"); } if (end == null) { throw new IllegalArgumentException("end cannot be null"); } current = start; this.end = end; } @Override public boolean hasNext() { return current != null; } @Override public LocalDate next() { if (current == null) { throw new NoSuchElementException(); } final LocalDate ret = current; current = current.plusDays(1); if (current.compareTo(end) > 0) { current = null; } return ret; } @Override public void remove() { throw new UnsupportedOperationException(); } } }