开始时间是2022-05-31 23:58:41,结束时间是2023-06-12 13:54:06,根据这个时间段作为范围条件,获取时间段内每个月的开始、结束时间的值,java代码怎么写
时间: 2024-03-03 20:47:04 浏览: 28
可以使用 Java 中的 Calendar 类来实现这个需求。具体实现代码如下:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateRange {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = null;
Date endDate = null;
try {
startDate = sdf.parse("2022-05-31 23:58:41");
endDate = sdf.parse("2023-06-12 13:54:06");
} catch (Exception e) {
e.printStackTrace();
}
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
while (startCal.before(endCal)) {
int year = startCal.get(Calendar.YEAR);
int month = startCal.get(Calendar.MONTH) + 1;
int day = 1;
startCal.set(year, month - 1, day, 0, 0, 0);
Date monthStartDate = startCal.getTime();
int lastDay = startCal.getActualMaximum(Calendar.DAY_OF_MONTH);
day = lastDay;
startCal.set(year, month - 1, day, 23, 59, 59);
Date monthEndDate = startCal.getTime();
System.out.println("Month " + month + " start date: " + sdf.format(monthStartDate));
System.out.println("Month " + month + " end date: " + sdf.format(monthEndDate));
startCal.add(Calendar.MONTH, 1);
}
}
}
```
这个代码会输出时间段内每个月的开始和结束时间的值,例如:
```
Month 6 start date: 2022-06-01 00:00:00
Month 6 end date: 2022-06-30 23:59:59
Month 7 start date: 2022-07-01 00:00:00
Month 7 end date: 2022-07-31 23:59:59
Month 8 start date: 2022-08-01 00:00:00
Month 8 end date: 2022-08-31 23:59:59
...
```