我强烈建议在07中使用
Joda-Time来处理有关日期操作的任何事情,因为它带来了很多有用的功能,使代码不那么复杂.
此代码使用JodaTime:
public static final List NON_WORKING_DAYS;
static {
List nonWorkingDays = new ArrayList();
nonWorkingDays.add(DateTimeConstants.SATURDAY);
nonWorkingDays.add(DateTimeConstants.SUNDAY);
NON_WORKING_DAYS = Collections.unmodifiableList(nonWorkingDays);
}
public static Minutes getMinsBetween(DateTime d1, DateTime d2,
boolean onlyBusinessDays) {
BaseDateTime startDate = onlyBusinessDays && !isBusinessDay(d1) ?
new DateMidnight(d1) : d1;
BaseDateTime endDate = onlyBusinessDays && !isBusinessDay(d2) ?
new DateMidnight(d2) : d2;
Minutes minutes = Minutes.minutesBetween(startDate, endDate);
if (onlyBusinessDays) {
DateTime d = new DateTime(startDate);
while (d.isBefore(endDate)) {
if (!isBusinessDay(d)) {
Duration dayDuration = new Duration(d, d.plusDays(1));
minutes = minutes.minus(int) dayDuration.getStandardMinutes());
}
d = d.plusDays(1);
}
}
return minutes;
}
private static boolean isBusinessDay(DateTime dateToCheck) {
return !NON_WORKING_DAYS.contains(dateToCheck.dayOfWeek().get());
}
测试此代码时,它会给出以下结果:
DateTime d1 = new DateTime(2013, 1, 4, 18, 0); // a Friday, 6 pm
DateTime d2 = new DateTime(2013, 1, 7, 6, 0); // the following Monday, 6 am
Minutes minutes = getMinsBetween(d1, d2, true);
System.out.println(minutes.toStandardHours().getHours()); // outputs "12" (in hours)
d1 = new DateTime(2013, 1, 5, 12, 0); // a Saturday, 12 pm
d2 = new DateTime(2013, 1, 6, 12, 0); // the following Sunday, 12 pm
minutes = getMinsBetween(d1, d2, true);
System.out.println(minutes.toStandardHours().getHours()); // outputs "0" (in hours)
d1 = new DateTime(2013, 1, 5, 12, 0); // a Saturday, 12 pm
d2 = new DateTime(2013, 1, 7, 6, 0); // the following Monday, 6 am
minutes = getMinsBetween(d1, d2, true);
System.out.println(minutes.toStandardHours().getHours()); // outputs "6" (in hours)
我刚刚测试了一个月周末变化的情况:从3月29日星期五(下午6点)到4月1日星期一(早上6点):
d1 = new DateTime(2013, 3, 29, 18, 0);
d2 = new DateTime(2013, 4, 1, 6, 0);
minutes = getMinsBetween(d1, d2, true);
System.out.println(minutes.toStandardHours().getHours());
结果是12个小时,因此适用于月份变化.
我的第一个解决方案是没有正确处理夏令时.我们必须确定减去分钟数的每个实际日期的持续时间,因为夏令时变化的天数不会是24小时:
if (!isBusinessDay(d)) {
Duration dayDuration = new Duration(d, d.plusDays(1));
minutes = minutes.minus(int) dayDuration.getStandardMinutes());
}