获取两个时间之间的月份

工具类

public static List<String> getMonthBetweenDate(Date startDate, Date endDate) {
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");//格式化,调整为自己需要的格式
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        //给calendar设置开始时间
        min.setTime(startDate);
        //set方法设置年月日 年为开始时间的年份 后面同理
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
        //给calendar设置结束时间
        max.setTime(endDate);
        //set方法设置年月日 年为结束时间的年份 后面同理,最后面的1和2不要改
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        //创建一个临时的变量,代表当前的时间
        Calendar curr = min;
        //如果当前的时间在结束时间之前,循环知道超过结束时间就结束,返回结果集合
        while (curr.before(max)) {
            //将这个当前的时间格式化之后保存到result集合
            result.add(sdf.format(curr.getTime()));
            //将当前的时间加上1个月
            curr.add(Calendar.MONTH, 1);
        }
        return result;
    }

测试方法  .format 是 date转string
                .parse 是 string转date

public static void main(String[] args) {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        String s = "2024-01-01 00:00:00";
        Date startDate = null;
        Date endDate = new Date();//当前时间2024.05.09
        try {
            startDate = format1.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        System.out.println("====== " + getMonthBetweenDate(startDate , endDate));
    }

结果

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Herbig

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值