java 生成昨天时间
时间: 2023-10-14 22:27:09 浏览: 46
可以使用Java 8中的LocalDate和LocalDateTime类来实现生成昨天的日期和时间。
生成昨天的日期:
```java
LocalDate yesterday = LocalDate.now().minusDays(1);
System.out.println("昨天的日期是:" + yesterday);
```
生成昨天的日期和时间:
```java
LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
System.out.println("昨天的日期和时间是:" + yesterday);
```
另外,也可以使用Calendar类来生成昨天的日期和时间:
```java
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
Date yesterday = calendar.getTime();
System.out.println("昨天的日期和时间是:" + yesterday);
```
不过需要注意的是,使用Calendar类生成的日期和时间是以Date对象的形式返回的,需要进行格式化后才能输出。
相关问题
java生成当前时间
要在 Java 中生成当前时间,你可以使用 `java.util.Date` 类或 `java.time.LocalDateTime` 类。以下是两种常见的方法:
使用 `java.util.Date` 类:
```java
import java.util.Date;
public class CurrentTimeExample {
public static void main(String[] args) {
Date currentTime = new Date();
System.out.println("当前时间为: " + currentTime);
}
}
```
使用 `java.time.LocalDateTime` 类(Java 8+):
```java
import java.time.LocalDateTime;
public class CurrentTimeExample {
public static void main(String[] args) {
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间为: " + currentTime);
}
}
```
这两种方法都可以获取当前的日期和时间。如果你只需要当前的日期或时间部分,你可以根据需要进一步处理 `Date` 或 `LocalDateTime` 对象。
用java生成当前时间
你好,可以使用以下代码生成当前时间:
```
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(date);
System.out.println("当前时间为:" + currentTime);
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)