Showing posts with label loop through date object. Show all posts
Showing posts with label loop through date object. Show all posts

Wednesday, April 14, 2010

java Date range Iterator

Tree easy steps to create your own Date Iterator to iterate though some date range.

Step 1: Implement java.util.Iterator & java.lang.Iterable interfaces
Step 2: implment the interface methods.
Step 3: start using your newly created class.


Below is a simple example:
---------------------------

package com.kal.util;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;

public class DateIterator implements Iterator, Iterable {

private Calendar end = null;
private Calendar start = null;

public DateIterator(Date start, Date end) {
this.end = Calendar.getInstance();
this.start = Calendar.getInstance();
this.start.setTime(start);
this.end.setTime(end);
this.end.add(Calendar.DATE, -1);
this.start.add(Calendar.DATE, -1);
}

//This has the condition to check whether start date has reached end date.
public boolean hasNext() {
return !start.after(end);
}

//increments one day.
public Date next() {
start.add(Calendar.DATE, 1);
return start.getTime();
}

//Either throw an exception or make it empty.
public void remove() {
throw new UnsupportedOperationException("Remove not supported");
}

public Iterator iterator() {
return this;
}


public static void main(String[] args) {

//For example, start date = end date - 1 month
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1);
Date startDate = cal.getTime();

Date endDate = new Date();

DateIterator itr = new DateIterator(startDate, endDate);

//This loop prints the last one month dates
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}