# Calculate no of weeks between dates

• 07-06-2011, 05:56 PM
pink123
Calculate no of weeks between dates
Hi,

I have a start date and an end date.
Start date is always a sunday and end date a saturday.
I have to calculate the no of weeks between the start date and end date.
I am confused about how to calculate when the enddate is in another year?
The maximum difference allowed is 26 weeks
I am using Calender.WeekofYear to calculate and then taking the differnce but this is giving wrong
results.
I am not clear about the week of year calculation concept.
For a given year ,The no of weeks is 52 ,sometimes its 53 and the next years first week is sometimes
1st week or at times 52.
Can anyone please explain this concept of finding no of weeks.

• 07-06-2011, 06:01 PM
JosAH
Have you read the API documentation for the GregoreanCalendar class (and its parent class, the Calendar class)?

kind regards,

Jos
• 07-06-2011, 06:09 PM
pink123
Thanks for the reply.I will read and come back with questions if any.
• 07-07-2011, 03:33 PM
pink123
I have read and have a few questions.
If my week starts on Sunday and Ends on saturday ,can I get a calender with weeks numbers?(Any document )
Are the week numbers going to be same as that provided by ISO ,ISO treats Monday as the start date or the week numbers will change if my start date for a week is a sunday?

Thanks
• 07-07-2011, 04:36 PM
JosAH
Reread the API documents for those two classes; the Calendar class has a setFirstDayOfWeek( ... ) method (I didn't even know that those days can differ per country ;-) Of course the week numbers change on those days.

kind regards,

Jos
• 07-07-2011, 05:57 PM
pink123
thanks for the reply.I tried to do it the way mentioned and it is giving me the desired results

int getDateDiff( Date d1, Date d2) {
if( d1.after(d2) ) { // make sure d1 < d2, else swap them
Date temp = d1;
d1 = d2;
d2 = temp;
}
GregorianCalendar c1 = new GregorianCalendar();
c1.setTime(d1);
GregorianCalendar c2 = new GregorianCalendar();
c2.setTime(d2);
for( long i=1; ; i++ ) {
if( c1.after(c2) )
return i;
}

I tested it and it is giving me correct weeks.Do you see any problem with this approach?
• 07-07-2011, 06:41 PM
JosAH
Quote:

Originally Posted by pink123
I tested it and it is giving me correct weeks.Do you see any problem with this approach?

Not reallly, no; as long as your end date is on a Saturday and your start date is on a Sunday (as you wrote) no rounding up occurs. The *Calendar interface is terrible (imho) but it does its job ;-)

kind regards,

Jos