要获取当前月份的上一个月的日期,可以使用Java中的Calendar类来实现。具体步骤如下:

  1. 使用Calendar.getInstance()方法获取当前日期和时间的Calendar对象。
  2. 使用Calendar类中的add()方法将月份减1,表示获取上一个月的日期。例如,使用Calendar.MONTH表示月份字段,并传入-1作为参数。
  3. 使用Calendar类中的get()方法获取上一个月的年份和月份。
  4. 使用SimpleDateFormat类将年份和月份格式化为日期字符串。

以下是完整的Java代码示例:

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

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

        // 将月份减1,获取上一个月的日期
        calendar.add(Calendar.MONTH, -1);

        // 获取上一个月的年份和月份
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始,需要加1

        // 格式化年份和月份为日期字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String lastMonth = sdf.format(calendar.getTime());

        System.out.println("上一个月的日期为:" + lastMonth);
    }
}

运行以上代码,将输出当前月份的上一个月的日期,例如:

上一个月的日期为:2021-09
``
java获取当前月份的上一个月的日期

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

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