根据时间段【2020-11-20 09:09:09,2021-10-09 10:10:10】先转换为【2020-11-20 00:00:00,2021-10-09 59:59:59】 再根据转换时间把里面的每一天获取出来 java
时间: 2023-12-03 13:43:28 浏览: 50
java时间的转换
可以使用 Java 中的 Date 类和 Calendar 类来完成该任务。具体的实现步骤如下:
1. 将时间字符串转换为 Date 对象,并设置时间为 00:00:00。
```java
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = dateFormat.parse("2020-11-20 09:09:09");
Date endDate = dateFormat.parse("2021-10-09 10:10:10");
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
startDate = calendar.getTime();
calendar.setTime(endDate);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
endDate = calendar.getTime();
```
2. 计算两个日期之间的天数,并将每一天的日期加入到 List 中。
```java
List<Date> dateList = new ArrayList<>();
calendar.setTime(startDate);
while (calendar.getTimeInMillis() <= endDate.getTime()) {
dateList.add(calendar.getTime());
calendar.add(Calendar.DATE, 1);
}
```
完整代码如下:
```java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DateUtils {
public static void main(String[] args) throws Exception {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = dateFormat.parse("2020-11-20 09:09:09");
Date endDate = dateFormat.parse("2021-10-09 10:10:10");
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
startDate = calendar.getTime();
calendar.setTime(endDate);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
endDate = calendar.getTime();
List<Date> dateList = new ArrayList<>();
calendar.setTime(startDate);
while (calendar.getTimeInMillis() <= endDate.getTime()) {
dateList.add(calendar.getTime());
calendar.add(Calendar.DATE, 1);
}
for (Date date : dateList) {
System.out.println(dateFormat.format(date));
}
}
}
```
阅读全文