直接上代码(注意这里使用了Hutool里面的DateUtil工具类):
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import java.text.ParseException;
import java.util.Date;
public class DateUtilPlus {
public static Integer getWeek(String beginDateStr, String endDateStr) {
DateTime beginDate = DateUtil.parseDate(beginDateStr);
DateTime endDate = DateUtil.parseDate(endDateStr);
DateTime currentDate = DateUtil.dateNew(new Date());
int week = 1;
if (DateUtil.isIn(currentDate, beginDate, endDate)) {
Date endDateOfWeek = DateUtil.endOfWeek(beginDate);
while (!DateUtil.isIn(currentDate, beginDate, endDateOfWeek)) {
++week;
endDateOfWeek = DateUtil.endOfWeek(DateUtil.offsetDay(endDateOfWeek, 1));
}
return week;
}
return null;
}
public static Integer getMonth(String beginDateStr, String endDateStr) {
DateTime beginDate = DateUtil.parseDate(beginDateStr);
DateTime endDate = DateUtil.parseDate(endDateStr);
DateTime currentDate = DateUtil.dateNew(new Date());
int month = 1;
if (DateUtil.isIn(currentDate, beginDate, endDate)) {
Date endDateOfMonth = DateUtil.endOfMonth(beginDate);
while (!DateUtil.isIn(currentDate, beginDate, endDateOfMonth)) {
++month;
endDateOfMonth = DateUtil.endOfMonth(DateUtil.offsetDay(endDateOfMonth, 1));
}
return month;
}
return null;
}
public static void main(String[] args) throws ParseException {
Integer week = DateUtilPlus.getWeek("2020-08-01", "2020-10-31");
Integer month = DateUtilPlus.getMonth("2020-08-01", "2020-10-31");
System.out.println("week--->" + week + " month--->" + month);
}