有一个startTime字段每个月根据该字段的号数与当月号数判断相等返回日期不相等返回null如果当月的号数小于startTime的号数则当月最后一天返回日期用Java写出获取下一个月的代码
以下是获取下一个月的代码,其中假设startTime是一个LocalDate类型的变量:
public LocalDate getNextMonthDate(LocalDate startTime) {
int startDay = startTime.getDayOfMonth();
int daysInMonth = startTime.getMonth().length(startTime.isLeapYear());
int currentDay = LocalDate.now().getDayOfMonth();
if (currentDay < startDay) {
return LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonthValue(), daysInMonth).plusMonths(1);
} else if (currentDay == startDay) {
return LocalDate.now();
} else {
return null;
}
}
这段代码首先获取了startTime的号数,以及当前月份的号数和天数。然后,根据规则判断下一个月的日期:
- 如果当前号数小于startTime的号数,则返回当月最后一天的日期加上一个月;
- 如果当前号数等于startTime的号数,则返回当前日期;
- 如果当前号数大于startTime的号数,则返回null。
原文地址: https://www.cveoy.top/t/topic/bQrs 著作权归作者所有。请勿转载和采集!