我在java中有一个约会,我想为它添加一定的工作时间。
但是,它应该考虑一个工作周。
8 Hours days (8:00 to 16:00),
和
no work on weekends (Saturday/Sunday).
所以我有Date object
给current time
。我还有double
,这是要添加到该日期的分钟数。这样做的最佳方式是什么?
I'm using Java 8.
一些例子:
在同一天工作:
Date date = new Date(2000, 1, 1, 8, 0); //so first of jan, 8:00. Let's assume this is a monday.
double minutes = 4 * 60;
Date newDate = addWorkingTime(date, minutes);
// newDate should be the same day, 12:00
多天工作:
Date date = new Date(2000, 1, 1, 14, 0); //so first of jan, 14:00. Let's assume this is a monday.
double minutes = 4 * 60;
Date newDate = addWorkingTime(date, minutes);
// newDate should be the next day, 10:00
// 2 hours on the first day, the next two hours of work on the next.
周末工作:
Date date = new Date(2000, 1, 5, 14, 0); //so fifth of jan, 14:00. Let's assume this is a friday.
double minutes = 8 * 60;
Date newDate = addWorkingTime(date, minutes);
// newDate should be the next monday, 14:00
// 2 hours on the first day, the next six hours of work the next monday.
谢谢!
答案 0 :(得分:0)
您可以使用此方法:
public static LocalDateTime addWorkingMinutes(LocalDateTime date, long minutes) {
if (date.getHour() < 8) {
// Working day hasn't started. Reset date to start of this working day
date = date.withHour(8).withMinute(0).withSecond(0);
}
// Take care of weekends
if (date.getDayOfWeek() == DayOfWeek.SATURDAY) {
date = date.plusDays(2);
} else if (date.getDayOfWeek() == DayOfWeek.SUNDAY) {
date = date.plusDays(1);
}
LocalDateTime endOfCurrentWorkingDay = date.withHour(16).withMinute(0).withSecond(0);
// Get minutes from date to endOfCurrentWorkingDay
long minutesCovered = ChronoUnit.MINUTES.between(date, endOfCurrentWorkingDay);
if (minutesCovered > minutes) {
// If minutesCovered covers the minutes value passed, that means result is the same working
// day. Just add minutes and return
return date.plusMinutes(minutes);
} else {
// Calculate remainingMinutes, and then recursively call this method with next working day
long remainingMinutes = minutes - minutesCovered;
return addWorkingMinutes(endOfCurrentWorkingDay.plusDays(1).withHour(8), remainingMinutes);
}
}
考虑到周末,测试了您的样本输入和我的一些其他输入。
注意:我使用的是Java 8 DateTime API,因为您已经使用Java 8了,所以仍然不应该使用Date
。