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)
I would strongly recommend using JodaTime (or DateTimeof Java8) for this, since the old Date/Calendar API is pretty useless.
public DateTime getEndtime(final DateTime startdate, final int hours) {
final DateTime endOfWeek = endOfWeek(startdate);
final Duration restOfWeek = new Duration(startdate, endOfWeek);
final Duration hoursDuration = toDuration(hours);
if (restOfWeek.isLongerThan(hoursDuration)) {
return startdate.plus(hoursDuration);
} else {
final Duration durationForNextWeek = hoursDuration.minus(restOfWeek);
return startOfWeek(startdate).plus(durationForNextWeek);
}
}
//Converts number of hours as int to Duration
private Duration toDuration(final int hours) {
return new Duration(hours * 60 * 60 * 1000);
}
//Returns coming friday, 1 millisecond to midnight
private DateTime endOfWeek(final DateTime dateTime) {
DateTime copy = dateTime;
while (copy.getDayOfWeek() != 6) {
copy = copy.plusDays(1);
}
return copy.toDateMidnight().toDateTime().minusMillis(1);
}
//Returns the following monday at midnight
//If dateTime is on a monday, the next monday will be chosen
private DateTime startOfWeek(final DateTime dateTime) {
DateTime copy = dateTime.plusDays(1);
while (copy.getDayOfWeek() != 1) {
copy = copy.plusDays(1);
}
return copy.toDateMidnight().toDateTime();
}
Explanation of the code:
This code NOT support tasks stretching over multiple weeks, but it's a start that you can modify to support this.. Might be some edge cases that aren't handled as well, I'll leave it to you to test it thoroughly.