Calculating days between certain dates with certain days being excluded using java Calendar
I'm trying to come up with a way to calculate the number of days between two different dates, however there will be certain days of the week that are only to be accounted for. For example, let's say we want to calculate the number of work days between 8/1 and 8/31, but employee only works Monday, Tuesday and Wednesday. The result would be that this employee only works 15 da开发者_Python百科ys during that period.
Has anyone put together something similar using the java Calendar class?
Try Joda Time, is the best solution to manage Date and Time.
The code of dogbane corrected:
final Calendar current = Calendar.getInstance();
current.set(2011, 7, 1);
final Calendar end = Calendar.getInstance();
end.set(2011, 7, 31);
int count = 0;
while (!current.after(end)) {
int dayOfWeek = current.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.MONDAY ||
dayOfWeek == Calendar.TUESDAY ||
dayOfWeek == Calendar.WEDNESDAY) {
count++;
}
current.add(Calendar.DAY_OF_MONTH, 1);
}
System.out.println(count);
If use Joda Time:
DateTime current = new DateTime(2011, 8, 1, 0, 0, 0, 0);
DateTime end = new DateTime(2011, 8, 31, 0, 0, 0, 0);
int count = 0;
while (!current.isAfter(end)) {
int dayOfWeek = current.getDayOfWeek();
if (dayOfWeek == DateTimeConstants.MONDAY || dayOfWeek == DateTimeConstants.TUESDAY
|| dayOfWeek == DateTimeConstants.WEDNESDAY) {
count++;
}
current = current.plusDays(1);
}
System.out.println(count);
You can do this by incrementing the date by one day until you reach the end date. At each iteration, check if the day is Mon, Tue or Wed and increment a counter.
For example:
final Calendar current = Calendar.getInstance();
current.set(2011, 7, 1);
final Calendar end = Calendar.getInstance();
end.set(2011, 7, 31);
int count = 0;
while (current.compareTo(end) != 0) {
current.add(Calendar.DAY_OF_MONTH, 1);
int dayOfWeek = current.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.MONDAY ||
dayOfWeek == Calendar.TUESDAY ||
dayOfWeek == Calendar.WEDNESDAY) {
count++;
}
}
System.out.println(count);
You could roll your own solution with java.util.Calendar; however, I suggest looking at some existing library, such as ObjectLab Kit date utilities.
精彩评论