Java获取给定月份的前N个月份和前N个季度

描述:

在项目开发过程中,遇到这样一个需求,即:给定某一月份,得到该月份前面的几个月份以及前面的几个季度。例如:给定2023-09,获取该月份前面的前3个月,即2023-08、2023-07、2023-06,以及该月份的前3个季度,即2023-06、2023-03、2022-12。

代码:

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        System.out.println(getMonthDate("2023-2", 5));
        System.out.println(getQuarterDate("2023-2", 4));

    }

    /**
     * 获取给定日期的前Num个月份
     * @param strDate   日期
     * @param num   个数
     * @return
     */
    public static List<String> getMonthDate(String strDate, int num){
        List<String> monthList = new ArrayList<>();
        for(int i=0; i < num; i++){
            monthList.add(generatePreDate(strDate, i));
        }
        return monthList;
    }
    /**
     * 获取给定日期的前Num个季度
     * @param strDate   日期
     * @param num   个数
     * @return
     */
    public static List<String> getQuarterDate(String strDate, int num){
        strDate = judgeQuarter(strDate);
        List<String> quarterList = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            quarterList.add(generatePreDate(strDate, i * 3));
        }
        return quarterList;
    }

    /**
     * 判断月份属于哪个季度
     * @param date
     * @return
     */
    public static String judgeQuarter(String date){
        String[] strs = date.split("-");
        String result = strs[0] + "-";
        int month = Integer.parseInt(strs[1]);
        if(month >= 1 && month <= 3){
            result += "03";
        }
        if(month >= 4 && month <= 6){
            result += "06";
        }
        if(month >= 7 && month <= 9){
            result += "09";
        }
        if(month >= 10 && month <= 12){
            result += "12";
        }
        return result;
    }


    public static String generatePreDate(String strDate, int num){
        String stringDate="";
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
            Date month=formatter.parse(strDate);
            Calendar calendar = Calendar.getInstance();//得到Calendar实例
            calendar.setTime(month);
            calendar.add(Calendar.MONTH, -num);
            Date starDate = calendar.getTime();//得到时间赋给Data
            stringDate = formatter.format(starDate);//使用格式化Data
            return stringDate;
        }catch (Exception e){
            e.printStackTrace();
            return stringDate;
        }
    }
}

实现结果:

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值