第一种方式:LocalDate 方式
public static void main(String[] args) {
String transferTime = "2024-04";
String curMonthDate = transferTime + "-01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// 将字符串转换为 LocalDate 对象
LocalDate date = LocalDate.parse(curMonthDate, formatter);
// 减去一个月
LocalDate previousMonthDate = date.minusMonths(1);
String preMonthDate = previousMonthDate.format(formatter);
System.out.println("上一个月===" + preMonthDate.substring(0, 7));
}
第二种方式:Calendar 方式
public static void main(String[] args) {
String transferTime = "2024-01";
String curMonthDate = transferTime + "-01";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date transferDate = format.parse(curMonthDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(transferDate);
calendar.add(Calendar.MONTH,-1); // 减一个月 为正数时 加 X 月
String month = format.format(calendar.getTime());
System.out.println("上一个月===" + month.substring(0, 7));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
09-18
1224
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-14
1847
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-23
714
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)