java 工作日,使用java指向上一个工作日

I am new with using java.calendar.api.

I want to point to the previous working day for a given day using java.

BUT the conditions goes on increasing when i am using calendar.api to manipulate dates

since I had to consider the usual weekends and the pointing to the previous month and also i had to consider the regional holidays in my region......

for ex:say i had to consider the U.S holidays and point to the day before that.

Is there any way i can define my own calendar and use it so that date manipulation senses all those usual changes?

解决方案

While you should consider using the Joda Time library, here's a start with the Java Calendar API:

public Date getPreviousWorkingDay(Date date) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

int dayOfWeek;

do {

cal.add(Calendar.DAY_OF_MONTH, -1);

dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

} while (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY);

return cal.getTime();

}

This only considers weekends. You'll have to add additional checks to handle days you consider holidays. For instance you could add || isHoliday(cal) to the while condition. Then implement that method, something like:

public boolean isHoliday(Calendar cal) {

int year = cal.get(Calendar.YEAR);

int month = cal.get(Calendar.MONTH) + 1;

int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

if (month == 12 && dayOfMonth == 25) {

return true;

}

// more checks

return false;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值