|
Java - Find date difference in days ignoring weekends |
|
|
|
|
Written by Steve Leonard
|
|
Thursday, 05 March 2009 11:42 |
|
One of the annoying tihings in Java is data handling. Here is a method to find the number of days between 2 calendar dates, ignoring weekends. Need to set these 2 variables. I have cut this from another class. I may at some point update this to have a generic example, but you should have enough to get by with on this. Calendar todaysCalendar; Calendar laterCalendar ; long MILLSECS_PER_DAY = 1000 * 60 * 60 * 24;
// Find number of calendar days between now and then. All in same // timezone and we are only using dates not times so this can be done // this way long endL = laterCalendar.getTimeInMillis() + laterCalendar.getTimeZone().getOffset( laterCalendar.getTimeInMillis()); long startL = todaysCalendar.getTimeInMillis() + todaysCalendar.getTimeZone().getOffset( todaysCalendar.getTimeInMillis()); long deltaDays = (endL - startL) / MILLISECS_PER_DAY;
// now remove weekends // First remove complete weeks int weekdays = 5 * ((int) deltaDays / 7);
// Now its as if we have less than one week between the days int leftover = (int) ((deltaDays) % 7); if (leftover > 0) { int fromday = todaysCalendar.get(Calendar.DAY_OF_WEEK); int move = fromday + leftover;
if (move > 7) { leftover -= 2; } weekdays += leftover; }
|
|
Last Updated on Thursday, 05 March 2009 13:12 |