最近公司有个需求,要取某个倍数的最近日期,如果当月的日期不满足条件,则取下个月的日期。
我的分析:
- 不能直接定义倍数规律,因为每个月的天数不太一样。
- 对参数进行日期格式化,保证日期是正确的。
- 分隔正确的日期,循环天数进行判断是否大于倍数(若小于则取下个月的日期)
@Test
public void testTime() {
//定义当前的日期
String time = "20200303";
//截取日期得到月和天
String month = time.substring(4, 6);
String day = time.substring(6);
log.info("输出月:{},日:{}", month, day);
//定义天的倍数
Integer div = 5;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = simpleDateFormat.parse(time);
Integer intDay = Integer.parseInt(day);
//循环判断参数日期是否小于天的倍数(如果是月初1号,小于倍数5,则取下个月最近的倍数日期)
while (intDay < div) {
//当前日期减去1天
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -1);
date = calendar.getTime();
log.info("输出日期:{}", simpleDateFormat.format(date));
intDay = date.getDay();
}
//得到新日期及获取对应年、月、日
String newTime = simpleDateFormat.format(date);
log.info("输出新日期:{}", newTime);
String newYear = newTime.substring(0, 4);
String newMonth = newTime.substring(4, 6);
String newDay = newTime.substring(6);
Integer days = Integer.parseInt(newDay);
//判断新日期除倍数后取余是否为0
for (int i = 1; i < days; i++) {
if (days % div == 0) {
newDay = days.toString();
break;
}
days--;
}
if (Integer.parseInt(newDay) < 10) {
newDay = "0" + newDay;
}
logger.info("输出最終日期:{}", newYear + newMonth + newDay);
} catch (Exception ex) {
log.error("异常输出:{}", ex);
}
}
运行结果为: