Days in a given date range for a given month.........

L

Lord0

Hi there,

I have an object with fields which represent dates and therefore a date
range.

private Date m_startDate;

private Date m_endDate;

Given another singular date (target) as an argument I want to return
all the days, in the range, where target.mon = dayrange.mon. Sorry for
the bad explanation. Maybe some examples:

If m_startDate is 15th Jan 06, m_endDate is 20th Mar 06 and target is
Jan 06

return: 15..31

If m_startDate is 15th Jan 06, m_endDate is 20th Mar 06 and target is
Feb 06

return 1..28[29]

If m_startDate is 15th Jan 06, m_endDate is 20th Mar 06 and target is
Mar 06

return 1..20

If m_startDate is 15th Jan 06, m_endDate is 20th Jan 06 and target is
Jan 06

return 15..20

This has fried my head and I am at a loss to think of a nice solution.

thanks in advance

Lord0
 
T

Thomas Weidenfeller

Lord0 said:
Hi there,

I have an object with fields which represent dates and therefore a date
range.

private Date m_startDate;

private Date m_endDate;

First of all, get rid of that annoying "m_" prefix. No one will steal
your variables while you look away, so no need to to mark them as "my
variables".

For the rest, here is a rough cut (untested). If I would have to code it
in real life I would first introduce a class like DateRange and provide
it with some intersection() method and a range Interator or similar.

GregorianCalendar start = new GregorianCalender();
start.setTime(m_startDate);
// probably reset time fields to zero

GregorianCalendar end = new GregorianCalendar();
end.setTime(m_endDate);
// probably reset time fields to zero

GregorianCalendar targetStart =
new GregorianCalendar(targetYear, targetMonth, 1);

GregorianCalendar targetEnd = (GregorianCalendar) targetStart.clone();
targetEnd.set(Calendar.DAY_OF_MONTH,
targetEnd.getActualMaximum(Calendar.DAY_OF_MONTH));

GregorianCalendar resultStart = start;
GregorianCalendar resultEnd = end;

if(targetStart.after(start) {
resultStart = targetStart;
}
if(targetEnd.before(end)) {
resultEnd = targetEnd;
}

while(resultEnd.after(resultStart)) {
System.out.println(resultStart);
resultStart.add(Calendar.DAY_OF_MONTH, 1);
}

This has fried my head and I am at a loss to think of a nice solution.

First it has to work. Then you can make it nice. E.g. by introducing the
above mentioned DateRange (or a CalendarRange) class.

/Thomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top