java获取当天每个小时的时间段
时间: 2023-10-18 10:10:40 浏览: 165
java获取某一时间
你可以使用 Java 中的 `LocalDateTime` 和 `DateTimeFormatter` 类来获取当天每个小时的时间段。以下是一个示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class HourlyTimeRanges {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < 24; i++) {
LocalDateTime start = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), i, 0, 0);
LocalDateTime end = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), i, 59, 59);
System.out.println("Hour " + i + ": " + start.format(formatter) + " - " + end.format(formatter));
}
}
}
```
运行该程序,将输出当前日期的每个小时的时间段,例如:
```
Hour 0: 2021-11-01 00:00:00 - 2021-11-01 00:59:59
Hour 1: 2021-11-01 01:00:00 - 2021-11-01 01:59:59
Hour 2: 2021-11-01 02:00:00 - 2021-11-01 02:59:59
...
Hour 22: 2021-11-01 22:00:00 - 2021-11-01 22:59:59
Hour 23: 2021-11-01 23:00:00 - 2021-11-01 23:59:59
```
阅读全文