date和string java
时间: 2023-08-29 21:10:22 浏览: 45
在Java中,可以使用SimpleDateFormat类来进行Date和String之间的转换。
要将Date类型转换为String类型,可以使用以下代码:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String formatStr = sdf.format(date);
System.out.println(formatStr);
```
这段代码将当前的Date对象转换为指定格式的字符串,并打印输出。
要将String类型转换为Date类型,可以使用以下代码:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatStr = "2022-05-31 13:54:20";
Date timeDate = null;
try {
timeDate = sdf.parse(formatStr);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(timeDate);
```
这段代码将指定格式的字符串转换为Date对象,并打印输出。
引用\[1\]中的代码示例演示了如何将Date转换为String类型,引用\[2\]和引用\[3\]中的代码示例演示了如何将String转换为Date类型。你可以根据需要选择适合的代码示例进行使用。
#### 引用[.reference_title]
- *1* [Java时间 Date转String,String转Date](https://blog.csdn.net/weixin_52014130/article/details/125064388)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [java中Date与String的相互转换](https://blog.csdn.net/Albert201605/article/details/120463528)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)