你可以使用java.util.Calendar类来获取上个月的年份和月份。下面是一个示例代码:

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();

        // 获取当前年份和月份
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);

        // 计算上个月的年份和月份
        if (month == 0) {
            year--;
            month = 11;
        } else {
            month--;
        }

        // 输出上个月的年份和月份
        System.out.println("上个月的年份:" + year);
        System.out.println("上个月的月份:" + (month + 1));
    }
}

这段代码首先获取当前日期,并将年份和月份分别保存到yearmonth变量中。然后根据月份的值进行判断,如果当前月份为1月,则需要将年份减1,并将月份设置为12月;否则,只需要将月份减1。最后,输出上个月的年份和月份。

运行以上代码,你将得到上个月的年份和月份


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

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