java date 格式化_Date类日期格式化
时间: 2023-09-27 08:08:21 浏览: 55
Java中的Date类可以使用SimpleDateFormat进行格式化,具体步骤如下:
1. 创建SimpleDateFormat对象,指定日期格式。
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
```
2. 调用SimpleDateFormat对象的format方法,将Date对象格式化为指定格式的字符串。
```java
Date date = new Date();
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
```
完整代码示例:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
```
输出结果:
```
2022-02-08 14:46:53
```
其中,SimpleDateFormat构造函数中的日期格式可以根据需要进行修改,具体格式化规则可以参考Java官方文档。