第一种方式:LocalDate 方式
public static void main(String[] args) {
String transferTime = "2024-04";
String curMonthDate = transferTime + "-01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
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);
String month = format.format(calendar.getTime());
System.out.println("上一个月===" + month.substring(0, 7));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}