Java8給出一個時間段,計算該時間范圍由哪些日期(天)和月份組成


1. 判斷時間段是否合法;

2. 循環判斷記錄數是否大於0

3. 根據起始時間算出該月的第一天、最后一天和這個月有多少天;

4. 判斷起始時間是否是該月第一天,如果是,再判斷結束時間與該月最后一天的大小:小於,等於,大於;

5. 判斷起始時間是否是該月第一天,如果不是,再判斷結束時間與該月最后一天的大小:小於,等於,大於;

 

這里的LocalDate是Java8中的時間類,只有日期,沒有時分秒等;如2018-03-26。

下面函數僅僅只需要接受兩個LocalDate參數(一個時間段),就可以獲得該時間段內由哪些日期和哪些月份組成;

Date、long轉LocalDate等更多時間常用操作可以參考:https://www.cnblogs.com/theRhyme/p/9756154.html

具體代碼如下:

public void accordingToCountCalcData(LocalDate start,LocalDate end){

    //這里的count表示自定義時間段內需要累加的記錄的條數 final long count = end.toEpochDay() - start.toEpochDay() + 1; if(count < 1){ log.error("startTime can't greater than endTime",new IllegalArgumentException("startTime can't greater than endTime")); return; } log.info("******BEGIN: There are {} records between {} and {}. ******",count,start,end); long num = count; while(num > 0) { LocalDate firstDay = start.with(TemporalAdjusters.firstDayOfMonth()); LocalDate lastDay = start.with(TemporalAdjusters.lastDayOfMonth()); //該月有多少天 int dayOfMonth = lastDay.getDayOfMonth(); if (firstDay.compareTo(start) == 0) { //傳入的起始時間如果是當月的第一天 if (lastDay.compareTo(end) == 0) { //傳入的結束時間和開始時間構成了完整一個月 num = num - lastDay.getDayOfMonth(); log.info("{} and {} which making up a full month",firstDay,lastDay); } else if (end.compareTo(lastDay) > 0) { //包含了完整的一個月 log.info("Accumulating {} to {} , {} records",start,lastDay,dayOfMonth); num = num - dayOfMonth; //下個月的這天 start = start.minusMonths(-1); //下個月的1號 start = LocalDate.of(start.getYear(),start.getMonthValue(),1); } else if (end.compareTo(lastDay) < 0) { log.info("Accumulating {} to {} , {} records.",start,end,num); num = 0; } }else if(start.compareTo(firstDay) > 0) { //傳入的開始時間不是當前月的第一天 if (end.compareTo(lastDay) <= 0) { log.info("Accumulating {} to {} , {} records.", start, end, num); num = 0; } else if (end.compareTo(lastDay) > 0) { //先累加從開始時間到這個月最后一天的記錄 Period p = Period.between(start, lastDay); //這里還減1是因為兩個日期如果相差11天,就有12條紀錄 int records = p.getDays() + 1; log.info("Accumulating {} to {} , {} records.", start, lastDay, records); num = num - records; //下個月的這天 start = start.minusMonths(-1); //下個月的1號 start = LocalDate.of(start.getYear(), start.getMonthValue(), 1); } } } log.info("****** End: Function \"accordingToCountCalcData\". ******"); }

測試結果如下:

 

 

在線日期工具:

https://tool.lu/timestamp/

http://www.ab126.com/clock/1639.html

https://bjtime.cn/riqi/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM