java中string转换成date
时间: 2023-10-01 14:03:51 浏览: 53
可以使用SimpleDateFormat类将String转换为Date。
例如,如果您有一个格式为“yyyy-MM-dd”的字符串,您可以使用以下代码将其转换为Date对象:
```
String dateString = "2021-07-22";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(dateString);
```
请注意,SimpleDateFormat的parse方法可能会抛出ParseException异常。因此,您应该在调用parse方法时使用try-catch块来捕获异常。
相关问题
java中 String 转换为 Date
在 Java 中,可以使用 SimpleDateFormat 类将 String 转换为 Date,具体步骤如下:
1. 创建一个 SimpleDateFormat 对象,设置日期格式。
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
```
2. 调用 SimpleDateFormat 的 parse 方法,将 String 转换为 Date。注意,parse 方法可能会抛出 ParseException 异常,需要进行处理。
```
String dateString = "2021-06-08 11:20:30";
Date date = null;
try {
date = sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
```
完整的代码示例如下:
```
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateExample {
public static void main(String[] args) {
// 创建 SimpleDateFormat 对象,设置日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将 String 转换为 Date
String dateString = "2021-06-08 11:20:30";
Date date = null;
try {
date = sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
// 输出结果
System.out.println("String: " + dateString);
System.out.println("Date: " + date);
}
}
```
需要注意的是,SimpleDateFormat 不是线程安全的,如果在多线程环境下使用,需要进行线程同步处理。此外,如果日期格式不正确,转换会失败并抛出异常。
java string 转化成 date
以下是Java中将字符串转换为日期的两种方法:
1. 使用SimpleDateFormat类:
```java
String str = "2021-01-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(str);
```
2. 使用DateTimeFormatter类(Java 8及以上版本):
```java
String str = "2021-01-01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(str, formatter);
```
相关推荐
![](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)