本文主要是介绍日期工具类-汇总当日到年底还剩下多少天,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*** @return 返回当日到当年最后一天一共多少天* @param currentDateStr 指定日期* @param pattern 日期类型* daysOfFeb: 二月天数* dayOfMonth:当日* j: 当月* arrThirtyFirst: 31天数组* arrThirty:30天数组* flag: 标志位 用来限定是否第一次访问,如果是第一次计算当月剩余天数,否则累加剩余天数*/public static int remainDays(String currentDateStr) {LocalDate now;if (StringUtils.isBlank(currentDateStr)) {now = LocalDate.now();} else {now = stringToLocalDate(currentDateStr, com.alibaba.excel.util.DateUtils.DATE_FORMAT_10);}int year = now.getYear();// 平年闰年判断boolean yearFlag = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0);int daysOfFeb = (yearFlag) ? 29 : 28;int dayOfMonth = now.getDayOfMonth();int j = now.getMonthValue();int[] arrThirtyFirst = {1, 3, 5, 7, 8, 10, 12};List<Integer> handledArrThirtyFirst = Arrays.stream(arrThirtyFirst).boxed().collect(Collectors.toList());int[] arrThirty = {4, 6, 9, 11};List<Integer> handledArrThirty = Arrays.stream(arrThirty).boxed().collect(Collectors.toList());boolean flag = true;int total = 0;if (j == 2) {total += daysOfFeb;}while (j > 0 && j < 13) {if (flag) {if (handledArrThirtyFirst.contains(j)) {total += 31 - dayOfMonth;}if (handledArrThirty.contains(j)) {total += 30 - dayOfMonth;}flag = false;} else {if (handledArrThirtyFirst.contains(j)) {total += 31;}if (handledArrThirty.contains(j)) {total += 30;}}j++;}return total;}
验证
@Testpublic void testRemainDays() {int count = DateUtil.remainDays(null);log.info("{}年还剩下{}天", LocalDate.now().getYear(), count);int cou = DateUtil.remainDays("2023-11-11");log.info("2023年还剩下{}天", cou);int first = DateUtil.remainDays("2024-12-01");log.info("2024年还剩下{}天", first);int second = DateUtil.remainDays("2024-02-01");log.info("2024年还剩下{}天", second);// 测试用例/*** 2024.06.12* 2024.02.01* 2024.12.01* 参数为空*/}
14:44:38.864 [main] INFO com.geekmice.springbootselfexercise.date.NoDaoTest - 2024年还剩下202天
14:44:38.882 [main] INFO com.geekmice.springbootselfexercise.date.NoDaoTest - 2023年还剩下50天
14:44:38.882 [main] INFO com.geekmice.springbootselfexercise.date.NoDaoTest - 2024年还剩下30天
14:44:38.883 [main] INFO com.geekmice.springbootselfexercise.date.NoDaoTest - 2024年还剩下335天
这篇关于日期工具类-汇总当日到年底还剩下多少天的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!