使用java指向上一个工作日 [英] pointing to previous working day using java

查看:795
本文介绍了使用java指向上一个工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用java.calendar.api的新手。
我想指出使用java的某一天的前一个工作日。
但是当我使用calendar.api操作日期
因为我不得不考虑通常的周末和指向上个月而且我不得不考虑我的区域假期时,情况会继续增加区域......

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?

推荐答案

虽然您应该考虑使用 Joda Time 库,但这里是Java Calendar API的一个开始:

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();
}

这只考虑周末。您必须添加额外的检查才能处理您考虑假期的日子。例如,您可以添加 || isHoliday(cal),而条件。然后实现该方法,例如:

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;
}

这篇关于使用java指向上一个工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆