我需要的是当前时间的 例如现在 是 2023-06-06 11:18 需要的是 前后一个小时中的每十分钟
时间: 2024-03-08 11:49:40 浏览: 16
好的,您可以使用 Java 8 中的 LocalDateTime 类来获取当前时间,然后按照您的需求生成时间序列。以下是一个示例代码,可以生成当前时间前后一个小时中,每 10 分钟的时间序列:
```java
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
public class TimeSeriesGenerator {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime startTime = now.minusHours(1).withMinute(0).withSecond(0).withNano(0);
LocalDateTime endTime = now.plusHours(1).withMinute(0).withSecond(0).withNano(0);
List<LocalDateTime> timeSeries = new ArrayList<>();
LocalDateTime currentTime = startTime;
while (currentTime.isBefore(endTime)) {
timeSeries.add(currentTime);
currentTime = currentTime.plusMinutes(10);
}
// 输出时间序列
for (LocalDateTime time : timeSeries) {
System.out.println(time);
}
}
}
```
解释一下代码:
首先,使用 `LocalDateTime.now()` 获取当前时间。然后,通过 `now.minusHours(1)` 和 `now.plusHours(1)` 得到当前时间前后一个小时的时间。接着,通过 `withMinute(0).withSecond(0).withNano(0)` 将这些时间的分钟、秒和纳秒都设置为 0,以保证只有整点的时间被包含在时间序列中。
接下来,使用一个 while 循环,从开始时间开始,每隔 10 分钟,生成一个时间,并将其加入到时间序列中。最后,输出时间序列。
您可以根据需要,修改代码中的时间间隔、时间范围等参数。