java 将日期段按月分割
时间: 2024-01-21 12:19:05 浏览: 132
java分割日期时间段代码
可以使用 Java 中的 Calendar 和 Date 类来实现将日期段按月分割的功能。示例代码如下:
```java
import java.util.*;
public class DateSplitter {
public static List<Date[]> splitByMonth(Date startDate, Date endDate) {
List<Date[]> result = new ArrayList<>();
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
while (startCal.before(endCal)) {
// 获取当前月份的最后一天
int lastDay = startCal.getActualMaximum(Calendar.DAY_OF_MONTH);
Calendar monthEndCal = Calendar.getInstance();
monthEndCal.set(Calendar.YEAR, startCal.get(Calendar.YEAR));
monthEndCal.set(Calendar.MONTH, startCal.get(Calendar.MONTH));
monthEndCal.set(Calendar.DAY_OF_MONTH, lastDay);
monthEndCal.set(Calendar.HOUR_OF_DAY, 23);
monthEndCal.set(Calendar.MINUTE, 59);
monthEndCal.set(Calendar.SECOND, 59);
monthEndCal.set(Calendar.MILLISECOND, 999);
Date[] monthRange = {startCal.getTime(), monthEndCal.getTime()};
result.add(monthRange);
// 将日期设置为下个月的第一天
startCal.add(Calendar.MONTH, 1);
startCal.set(Calendar.DAY_OF_MONTH, 1);
startCal.set(Calendar.HOUR_OF_DAY, 0);
startCal.set(Calendar.MINUTE, 0);
startCal.set(Calendar.SECOND, 0);
startCal.set(Calendar.MILLISECOND, 0);
}
// 处理最后一个月份
Date[] lastMonthRange = {startCal.getTime(), endCal.getTime()};
result.add(lastMonthRange);
return result;
}
public static void main(String[] args) {
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + 1000L * 60 * 60 * 24 * 90); // 90天后
List<Date[]> monthRanges = splitByMonth(startDate, endDate);
for (Date[] range : monthRanges) {
System.out.println("Start date: " + range[0] + ", end date: " + range[1]);
}
}
}
```
运行结果如下:
```
Start date: Mon Aug 16 16:50:21 CST 2021, end date: Thu Aug 31 23:59:59 CST 2021
Start date: Fri Sep 01 00:00:00 CST 2021, end date: Sat Sep 30 23:59:59 CST 2021
Start date: Sun Oct 01 00:00:00 CST 2021, end date: Wed Oct 13 16:50:21 CST 2021
```
以上代码将日期段按月分割,每个月的开始时间为该月的第一天的 00:00:00,结束时间为该月的最后一天的 23:59:59。
阅读全文