写一个 获取两个时间内所有小时的工具类,结果放入一个list中,list中存放 yyyy-MM-dd HI:mom:ss
时间: 2024-05-07 21:23:48 浏览: 75
以下是一个Java实现的工具类,可以获取两个时间内的所有小时,并将结果存放在List中:
```java
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class HourListGenerator {
public static List<String> generateHourList(Date start, Date end) {
List<String> hourList = new ArrayList<String>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(start);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while (calendar.getTime().before(end)) {
hourList.add(dateFormat.format(calendar.getTime()));
calendar.add(Calendar.HOUR_OF_DAY, 1);
}
return hourList;
}
}
```
使用示例:
```java
Date start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-01-01 00:00:00");
Date end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-01-02 00:00:00");
List<String> hourList = HourListGenerator.generateHourList(start, end);
for (String hour : hourList) {
System.out.println(hour);
}
```
输出结果:
```
2021-01-01 00:00:00
2021-01-01 01:00:00
2021-01-01 02:00:00
2021-01-01 03:00:00
2021-01-01 04:00:00
2021-01-01 05:00:00
2021-01-01 06:00:00
2021-01-01 07:00:00
2021-01-01 08:00:00
2021-01-01 09:00:00
2021-01-01 10:00:00
2021-01-01 11:00:00
2021-01-01 12:00:00
2021-01-01 13:00:00
2021-01-01 14:00:00
2021-01-01 15:00:00
2021-01-01 16:00:00
2021-01-01 17:00:00
2021-01-01 18:00:00
2021-01-01 19:00:00
2021-01-01 20:00:00
2021-01-01 21:00:00
2021-01-01 22:00:00
2021-01-01 23:00:00
```
阅读全文