java设置周末不可选_如何使用Java日历忽略周末?

我强烈建议在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());

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值