java String字符串转换成Date时间
时间: 2024-01-21 21:04:21 浏览: 35
在Java中,可以使用SimpleDateFormat类将字符串转换为Date类型的时间。下面是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateExample {
public static void main(String[] args) {
String strDate = "2022-11-11 11:11:11";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = formatter.parse(strDate);
System.out.println(date);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先定义了一个字符串表示时间,然后创建了一个SimpleDateFormat对象,指定日期时间的格式为“yyyy-MM-dd HH:mm:ss”。最后,我们使用parse方法将字符串转换为Date类型的时间对象。
相关问题
Java 时间格式的 字符串 转换成Date类型
可以使用SimpleDateFormat类的parse方法将字符串转换成Date类型,代码如下:
```
String str = "2021-05-01 12:30:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = sdf.parse(str);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
```
Java string字符串转date 补0
在Java中,可以使用SimpleDateFormat类将字符串转换为Date类型。而对于日期中的月份和日,如果不足两位数,需要在前面补0。可以使用String.format()方法来实现。
例如,将字符串"2021-5-1"转换为Date类型:
```java
String dateString = "2021-5-1";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(String.format("%1$04d-%2$02d-%3$02d",
Integer.parseInt(dateString.substring(0, 4)),
Integer.parseInt(dateString.substring(5, 6)),
Integer.parseInt(dateString.substring(7))));
System.out.println(date);
```
输出结果为:
```
Sat May 01 00:00:00 CST 2021
```
其中,String.format()方法中的%1$04d表示第一个参数需要占据4位,不足4位时在前面补0;%2$02d和%3$02d同理。substring()方法用于截取字符串中的年、月、日部分,并将其转换为整数类型。最后,将拼接后的字符串传入SimpleDateFormat的parse()方法中即可得到对应的Date类型。
相关推荐
![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)