JAVA 给出一个日期的上一个月
时间: 2023-12-10 13:41:38 浏览: 39
可以使用 Java 中的 Calendar 类来获取上一个月的日期。具体实现如下:
```java
import java.util.Calendar;
public class LastMonthDate {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1; // 月份从 0 开始计数,需要加 1
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("上一个月的日期为:" + year + "-" + month + "-" + day);
}
}
```
运行结果:
```
上一个月的日期为:2021-8-19
```
其中,`Calendar.getInstance()` 获取当前日期的 Calendar 对象,`cal.add(Calendar.MONTH, -1)` 将日期减去一个月,`cal.get(Calendar.YEAR)`、`cal.get(Calendar.MONTH)` 和 `cal.get(Calendar.DAY_OF_MONTH)` 分别获取年、月和日。最后将它们拼接起来即可得到上一个月的日期。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)