java 10的倍数_java取最近大于N倍数的日期

取某个倍数的最近日期,如果当月的日期不满足条件,则取下个月的日期。

我的分析:

不能直接定义倍数规律,因为每个月的天数不太一样。

对参数进行日期格式化,保证日期是正确的。

分隔正确的日期,循环天数进行判断是否大于倍数(若小于则取下个月的日期)

@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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值