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
362 views
in Technique[技术] by (71.8m points)

android - How to add Business hours to Date considering not adding weekends ? - Java

I want to add certain number of hours to date, ignoring the weekends

For example,

(Friday 18:00) + 48 = (Tuseday 18:00) (Saturday and Sunday are ignored)

since the company works 24 hours, business hours are 24. But still i could not get how to add hours only on business days

function can be something like:

public Date getTaskEndTime(Calendar startDate, int hours){
   // calculate the end time by adding the hours ignoring the weekends
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Add hours in steps not bigger then 24hours. And check after each step if you end up on a saturday or sunday. In each case add another 24hours. That should do what you want.

public Date getTaskEndTime(Calendar startDate, int hours){
    while (hours > 0){
        int step = 0;
        if(hours > 24) step = 24;
        else step = hours;          
        hours -= step;          
        startDate.add(Calendar.HOUR_OF_DAY, step);          
        int dayOfWeek = startDate.get(Calendar.DAY_OF_WEEK);
        if(dayOfWeek == Calendar.SATURDAY) hours += 24;
        if(dayOfWeek == Calendar.SUNDAY) hours += 24;
    }
    return startDate.getTime();
}

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

...