Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

pointing to previous working day using 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...