可以使用SimpleDateFormat类和Calendar类来实现:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        String yearMonth = "202308";
        String lastMonth = getLastMonth(yearMonth);
        System.out.println("上月的年月为:" + lastMonth);
    }

    public static String getLastMonth(String yearMonth) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        try {
            Date date = sdf.parse(yearMonth);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MONTH, -1);
            return sdf.format(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

输出结果为:

上月的年月为:202307
``
java 根据String年月202308 获取上月的String年月

原文地址: http://www.cveoy.top/t/topic/iXxI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录