java获取当前日期
时间: 2023-07-01 14:17:37 浏览: 37
可以使用Java中的Date类和SimpleDateFormat类来获取当前日期。
以下是一个简单的示例代码:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class GetDateExample {
public static void main(String[] args) {
// 创建一个Date对象,表示当前时间
Date date = new Date();
// 创建一个SimpleDateFormat对象,指定日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 使用SimpleDateFormat对象格式化Date对象,得到字符串表示的日期
String dateString = sdf.format(date);
// 打印日期
System.out.println("当前日期:" + dateString);
}
}
```
执行以上代码,输出结果如下:
```
当前日期:2021-09-14
```
相关问题
java 获取当前日期
在 Java 中,可以使用 `java.util.Date` 类来表示当前日期和时间。获取当前日期的方法如下:
```java
import java.util.Date;
public class GetCurrentDateExample {
public static void main(String[] args) {
Date currentDate = new Date();
System.out.println("Current Date: " + currentDate);
}
}
```
上述代码中,我们通过调用 `new Date()` 方法创建了一个 `Date` 对象,它表示当前日期和时间。然后,使用 `System.out.println()` 方法将当前日期打印到控制台。
输出结果类似于以下内容:
```
Current Date: Wed Aug 18 16:57:49 CST 2021
```
需要注意的是,`java.util.Date` 类已经过时,推荐使用 `java.time` 包中的新日期时间 API。如果你使用的是 Java 8 或以上的版本,可以使用 `java.time.LocalDateTime` 类获取当前日期和时间。
```java
import java.time.LocalDateTime;
public class GetCurrentDateExample {
public static void main(String[] args) {
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current Date and Time: " + currentDateTime);
}
}
```
输出结果类似于以下内容:
```
Current Date and Time: 2021-08-18T17:03:12.728
```
java 获取当前日期时间
获取当前日期时间可以使用Java中的`java.time`包中的`LocalDateTime`类。以下是获取当前日期时间的示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatDateTime = now.format(formatter);
System.out.println("当前日期时间: " + formatDateTime);
}
}
```
输出结果为:
```
当前日期时间: 2021-10-20 16:30:00
```
其中,`LocalDateTime.now()`方法获取当前日期时间,`DateTimeFormatter`类用于格式化日期时间,`ofPattern()`方法指定日期时间格式,`format()`方法将日期时间格式化为字符串。