java把Date类型转为yyyy-MM-dd HH:mm:ss格式的字符串
时间: 2024-06-15 13:03:48 浏览: 48
要将Java中的Date类型转换为指定格式的字符串,可以使用SimpleDateFormat类。以下是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateToStringExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
```
在上面的代码中,我们创建了一个SimpleDateFormat对象,并指定了日期格式为"yyyy-MM-dd HH:mm:ss"。然后,使用format()方法将Date对象转换为字符串。
相关问题
Java new date转为yyyy-mm-dd HH:MM:SS格式
可以使用SimpleDateFormat类来将Java的Date对象转换为指定格式的字符串。
示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateFormat.format(now);
System.out.println(formattedDate);
}
}
```
输出结果:
```
2021-11-18 12:34:56
```
在上面的示例中,我们首先创建了一个Date对象表示当前时间,然后创建了一个SimpleDateFormat对象,指定输出的格式为"yyyy-MM-dd HH:mm:ss",最后调用dateFormat.format方法将Date对象转换为字符串。
yyyy-MM-dd'T'HH:mm:ss转yyyy-MM-dd HH:mm:ss
要将yyyy-MM-dd'T'HH:mm:ss格式的日期时间转换为yyyy-MM-dd HH:mm:ss格式,可以按照以下步骤进行转换:
1. 首先,将输入的字符串解析为日期时间对象。可以使用Java中的SimpleDateFormat类来实现。示例代码如下:
```java
String inputDateTime = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = inputFormat.parse(inputDateTime);
```
2. 接下来,将日期时间对象格式化为目标格式的字符串。同样使用SimpleDateFormat类,示例代码如下:
```java
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String outputDateTime = outputFormat.format(date);
```
最后,outputDateTime就是转换后的yyyy-MM-dd HH:mm:ss格式的日期时间字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)