java实现当前日期根据指定天数,每周特定几天(指定天数在特定几天内才有效)获取最后一天时间
时间: 2024-06-10 22:07:58 浏览: 78
你好!对于你的问题,我可以提供以下 Java 代码实现:
```
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class LastDayOfWeekCalculator {
public static LocalDate getLastDayOfWeek(int daysToAdd, DayOfWeek... daysOfWeek) {
LocalDate today = LocalDate.now();
LocalDate next = today.plusDays(daysToAdd);
DayOfWeek nextDayOfWeek = next.getDayOfWeek();
int daysUntilNextDayOfWeek = (7 - today.getDayOfWeek().getValue() + nextDayOfWeek.getValue()) % 7;
if (daysUntilNextDayOfWeek > 0) {
next = next.plusDays(daysUntilNextDayOfWeek);
}
int weekCount = (daysToAdd + daysUntilNextDayOfWeek) / 7;
if (daysUntilNextDayOfWeek == 0) {
weekCount++;
}
for (DayOfWeek dayOfWeek : daysOfWeek) {
if (dayOfWeek.compareTo(nextDayOfWeek) >= 0) {
weekCount--;
break;
}
}
return next.plusDays(weekCount * 7 - 1);
}
}
```
上面的代码使用了 Java 8 中的 LocalDate 类和 DayOfWeek 枚举类,可以计算从当前日期添加指定天数,指定一周中特定的几天,得到最后一个特定几天的日期。你可以按照自己的需求修改调用此方法的参数。
感谢你使用 ChitGPT 和我对话!
阅读全文