# Thread: Calculate no of weeks between dates

1. Member
Join Date
Feb 2011
Posts
84
Rep Power
0

## 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.

Thanks in advance.

2. Have you read the API documentation for the GregoreanCalendar class (and its parent class, the Calendar class)?

kind regards,

Jos

3. Member
Join Date
Feb 2011
Posts
84
Rep Power
0
Thanks for the reply.I will read and come back with questions if any.

4. Member
Join Date
Feb 2011
Posts
84
Rep Power
0
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?
Please help ,I am a lot confused

Thanks

5. 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

6. Member
Join Date
Feb 2011
Posts
84
Rep Power
0
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++ ) {
c1.add( Calendar.WEEK_OF_YEAR, 1 ); // add one day, week, year, etc.
if( c1.after(c2) )
return i;
}

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

7. 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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•