字符串转成年月格式Date类型
时间: 2023-10-03 22:04:45 浏览: 48
要将字符串转换为年月格式的Date类型,您可以使用SimpleDateFormat类来实现。
下面是一个示例代码:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
String dateString = "2022-11";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
try {
Date date = format.parse(dateString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们首先创建了一个SimpleDateFormat对象,并指定了日期格式为"yyyy-MM",即年份和月份。然后,我们使用parse()方法将字符串转换为Date对象。
请注意,如果输入的字符串不符合指定的日期格式,会抛出ParseException异常。因此,请确保输入的字符串与指定的日期格式匹配。
运行上述代码,将输出转换后的Date对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![bat](https://img-home.csdnimg.cn/images/20210720083646.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)