Java 获取当天0点到23点的小时字符串类型集合
时间: 2023-07-16 19:15:01 浏览: 124
可以使用Java 8中的Stream API和DateTimeFormatter类来获取当天0点到23点的小时字符串类型集合。下面是示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class HourList {
public static void main(String[] args) {
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 定义时间格式化器
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 获取当天0点时间
LocalDateTime startOfDay = now.withHour(0).withMinute(0).withSecond(0).withNano(0);
// 获取当天0点到23点的小时字符串类型集合
List<String> hourList = IntStream.range(0, 24)
.mapToObj(hour -> startOfDay.plusHours(hour).format(formatter))
.collect(Collectors.toList());
// 打印结果
System.out.println(hourList);
}
}
```
输出结果为:
```
[2022-02-21 00:00:00, 2022-02-21 01:00:00, 2022-02-21 02:00:00, 2022-02-21 03:00:00, 2022-02-21 04:00:00, 2022-02-21 05:00:00, 2022-02-21 06:00:00, 2022-02-21 07:00:00, 2022-02-21 08:00:00, 2022-02-21 09:00:00, 2022-02-21 10:00:00, 2022-02-21 11:00:00, 2022-02-21 12:00:00, 2022-02-21 13:00:00, 2022-02-21 14:00:00, 2022-02-21 15:00:00, 2022-02-21 16:00:00, 2022-02-21 17:00:00, 2022-02-21 18:00:00, 2022-02-21 19:00:00, 2022-02-21 20:00:00, 2022-02-21 21:00:00, 2022-02-21 22:00:00, 2022-02-21 23:00:00]
```
阅读全文