java计算月份所在的季度

  • Post author:
  • Post category:java




java计算月份所在的季度:(月份+2)/ 3

下班的时候无意中看到同事写的根据月份计算季度的代码:

    /**
     * 获取两个时间内的季度集合
     * 返回结果说明 quarterList1["2019-1"] quarterList2["2019年1季度"]
     *
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
	public static Map<String, List<String>> getQuartersBetweenTwoDate(Date startDate, Date endDate) throws Exception {
        Map<String, List<String>> map = new HashMap<>(2);
        List<String> quarterList1 = new ArrayList<>();
        List<String> quarterList2 = new ArrayList<>();
        List<String> monthList = DateUtil.getMonthDateBetweenTwoDate(startDate, endDate);
        for (String dateStr : monthList) {
            Date date = DateUtil.parseDate(dateStr + "-01");
            int year = DateUtil.getYY(date);
            int month = DateUtil.getMM(date);
            String quarter = "", quarter1 = "", quarter2 = "";
            if (month >= 1 && month <= 3) {
                quarter = "1";
            } else if (month >= 4 && month <= 6) {
                quarter = "2";
            } else if (month >= 7 && month <= 9) {
                quarter = "3";
            } else if (month >= 10 && month <= 12) {
                quarter = "4";
            }
            quarter1 = year + "-" + quarter;
            quarter2 = year + "年" + quarter + "季度";
            if (!quarterList1.contains(quarter1)) {
                quarterList1.add(quarter1);
            }
            if (!quarterList2.contains(quarter2)) {
                quarterList2.add(quarter2);
            }
        }
        map.put("quarterList1", quarterList1);
        map.put("quarterList2", quarterList2);
        return map;
    }

头皮一阵发麻……

难道除了以下这种方式真的没有最优解了吗?

if (month >= 1 && month <= 3) {
    quarter = "1";
} else if (month >= 4 && month <= 6) {
    quarter = "2";
} else if (month >= 7 && month <= 9) {
    quarter = "3";
} else if (month >= 10 && month <= 12) {
    quarter = "4";
}

打开excel找找规律:

在这里插入图片描述

等等,好像发现了些什么。。。

3、6、9、12都正好是3的整数倍!!!

import java.util.Calendar;
import java.util.Date;
public class TestDate {
    
    public static void main(String[] args) {
        //模拟一波月份
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
        for (int i = 0; i < arr.length; i++) {
            //月份对应季度
            int quarter = (arr[i] + 2) / 3;
            System.out.println(arr[i] + "月对应季度:" + quarter);
        }
    }

    /**
     * 获取日期的月份
     *
     * @param date 日期
     * @return 月份
     */
    public static int getMM(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }
}

对应月份的季度:

1月对应季度:1
2月对应季度:1
3月对应季度:1
4月对应季度:2
5月对应季度:2
6月对应季度:2
7月对应季度:3
8月对应季度:3
9月对应季度:3
10月对应季度:4
11月对应季度:4
12月对应季度:4

头皮不麻了。



版权声明:本文为ChengXuYuanXingCheng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。