java怎么截取一串日期的年月
时间: 2023-09-09 19:10:21 浏览: 109
可以通过Java中的SimpleDateFormat类来实现日期格式化和解析。以截取年月为例,可以按照以下步骤进行操作:
1. 创建SimpleDateFormat对象,指定日期格式。
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
```
2. 使用parse方法将日期字符串解析为Date对象。
```java
Date date = sdf.parse("2022-01-01");
```
3. 使用Calendar对象获取年月。
```java
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
```
完整代码如下:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("2022-01-01");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
System.out.println("年份:" + year);
System.out.println("月份:" + month);
}
}
```
输出结果为:
```
年份:2022
月份:1
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.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/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)