views:

1737

answers:

2

Hi all,
I'm trying to implement without success a Date iterator with Joda time.
I need something that allows me to iterate all the days form startDate to endDate
Do you have any idea on how to do that?

+6  A: 

Here's something to get you started. You may want to think about whether you want it to be inclusive or exclusive at the end, etc.

import org.joda.time.*;
import java.util.*;

class LocalDateRange implements Iterable<LocalDate>
{
    private final LocalDate start;
    private final LocalDate end;

    public LocalDateRange(LocalDate start,
                          LocalDate end)
    {
        this.start = start;
        this.end = end;
    }

    public Iterator<LocalDate> iterator()
    {
        return new LocalDateRangeIterator(start, end);
    }

    private static class LocalDateRangeIterator implements Iterator<LocalDate>
    {
        private LocalDate current;
        private final LocalDate end;

        private LocalDateRangeIterator(LocalDate start,
                                       LocalDate end)
        {
            this.current = start;
            this.end = end;
        }

        public boolean hasNext()
        {
            return current != null;
        }

        public LocalDate next()
        {
            if (current == null)
            {
                throw new NoSuchElementException();
            }
            LocalDate ret = current;
            current = current.plusDays(1);
            if (current.compareTo(end) > 0)
            {
                current = null;
            }
            return ret;
        }

        public void remove()
        {
            throw new UnsupportedOperationException();
        }
    }
}

class Test
{
    public static void main(String args[])
    {
        LocalDate start = new LocalDate(2009, 7, 20);
        LocalDate end = new LocalDate(2009, 8, 3);
        for (LocalDate date : new LocalDateRange(start, end))
        {
            System.out.println(date);
        }
    }
}

It's a while since I've written an iterator in Java, so I hope it's right. I think it's pretty much okay...

Oh for C# iterator blocks, that's all I can say...

Jon Skeet
Thank you, this just made my life at least 900% easier.
Lotus Notes
A: 

http://code.google.com/p/google-rfc-2445 ?