java获取前一天整点时间最少最优代码案例
时间: 2023-07-09 16:37:40 浏览: 61
你可以使用`java.time`包中的`LocalDateTime`类来获取前一天的整点时间,下面是代码示例:
```java
// 获取当前时间的前一天
LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
// 获取前一天的整点时间
LocalDateTime lastHour = yesterday.withMinute(0).withSecond(0).withNano(0);
// 将LocalDateTime转换为Date对象
Date date = Date.from(lastHour.atZone(ZoneId.systemDefault()).toInstant());
```
这段代码会获取当前时间的前一天的整点时间,即将时间设置为前一天的0点0分0秒。它使用了`LocalDateTime`的方法链来设置时间,并通过`atZone()`方法将时间转换为`ZoneId.systemDefault()`时区的`ZonedDateTime`对象,最后通过`toInstant()`方法将`ZonedDateTime`对象转换为`Instant`对象,再通过`Date.from()`方法将`Instant`对象转换为`Date`对象。
这段代码较为简洁,使用了Java 8引入的新时间API,代码可读性高,建议使用。
相关问题
java获取前一天整点时间
你可以使用Java中的Calendar类和Date类来获取前一天的整点时间。下面是一个示例代码:
```java
// 获取当前时间的Calendar实例
Calendar calendar = Calendar.getInstance();
// 将时间设置为前一天
calendar.add(Calendar.DAY_OF_MONTH, -1);
// 将分、秒、毫秒设置为0,获取整点时间
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
// 获取前一天的整点时间
Date date = calendar.getTime();
```
这段代码会获取当前时间的前一天的整点时间,即将时间设置为前一天的0点0分0秒。你可以根据需求调整代码中的时间设置。
java打印出近3天的整点时间代码
以下是 Java 代码,可以打印出当前时间往前推三天的整点时间:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 循环打印近3天的整点时间
for (int i = 0; i < 72; i++) {
// 格式化时间
String formattedTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:00:00"));
System.out.println(formattedTime);
// 减去1小时
now = now.minusHours(1);
}
}
}
```
代码中,我们使用了 Java 8 中的 `LocalDateTime` 类来表示时间,并使用 `DateTimeFormatter` 对象来格式化时间。循环打印近3天的整点时间时,我们通过 `minusHours` 方法来减去1小时的时间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)