String 转 data
时间: 2024-06-09 15:05:50 浏览: 17
要将String类型转换为Date类型,可以使用SimpleDateFormat类的parse()方法。首先,需要创建一个SimpleDateFormat对象,并指定日期格式。例如,如果String类型的日期是"2020-11-01 08:30:20",则可以使用以下代码进行转换:
```java
String dateString = "2020-11-01 08:30:20";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(dateString);
```
在上述代码中,我们首先定义了一个String类型的日期字符串dateString,然后创建了一个SimpleDateFormat对象dateFormat,并通过构造方法将日期格式指定为"yyyy-MM-dd HH:mm:ss"。接下来,使用dateFormat的parse()方法将字符串dateString转换为Date类型的date。
需要注意的是,使用SimpleDateFormat的parse()方法时,需要处理ParseException异常。因此,在实际使用时,应该使用try-catch语句来捕获可能抛出的异常。例如:
```java
String dateString = "2020-11-01 08:30:20";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date;
try {
date = dateFormat.parse(dateString);
} catch (ParseException e) {
// 处理异常
e.printStackTrace();
}
```
以上是将String转换为Date的方法。如果需要将Date类型转换为String类型,可以使用SimpleDateFormat类的format()方法。例如:
```java
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = dateFormat.format(date);
```
在上述代码中,我们创建了一个Date对象date,然后使用SimpleDateFormat的format()方法将Date对象转换为String类型的dateString。同样,需要注意处理可能抛出的异常。
综上所述,可以使用SimpleDateFormat类来实现String类型到Date类型的转换,以及Date类型到String类型的转换。
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)