java通过年月获取当前月所有周(跨月),获取每周开始日期和结束日期

	    /**
         *    根据年月返回本月共几周,每周开始与结束日期
         */
        public static List> queryWeek(String year, String month) throws ParseException {
		/** 周 **/
		final String[] weeks = { "第一周", "第二周", "第三周", "第四周", "第五周", "第六周" };
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
		    calendar.setTime(sdf.parse(year + "-" + month + "-01"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
		int i = calendar.get(Calendar.DAY_OF_WEEK);
		int months = calendar.get(Calendar.MONTH);
		switch (i) {
		case 1:
			calendar.add(Calendar.DATE, 1);
			break;
		case 2:
			calendar.add(Calendar.DATE, 0);
			break;
		case 3:
			calendar.add(Calendar.DATE, 6);
			break;
		case 4:
			calendar.add(Calendar.DATE, 5);
			break;
		case 5:
			calendar.add(Calendar.DATE, 4);
			break;
		case 6:
			calendar.add(Calendar.DATE, 3);
			break;
		case 7:
			calendar.add(Calendar.DATE, 2);
			break;
		default:
			break;
		}
		// 本月的第一个星期
		List> list = new ArrayList>();
		int index = 0;
		while (true) {
			if (index++ > 0){
                calendar.add(Calendar.DATE, 1);
            }
			Map map = new HashMap();
			map.put("start", sdf.format(calendar.getTime()));
			calendar.add(Calendar.DATE, 6);
			map.put("end", sdf.format(calendar.getTime()));
			map.put("week", weeks[index - 1]);
			list.add(map);
			// 判断是否跨月
			if (months != calendar.get(Calendar.MONTH)){
				break;
            }
		}
		return list;
	}


测试:

	public static void main(String[] args) throws Exception {
		List> list = queryWeek("2023","10");
		System.out.println(list);
	}




打印结果:


[
    { week=第一周, start=2023-10-02, end=2023-10-08 },      
    { week=第二周, start=2023-10-09, end=2023-10-15 },           
    { week=第三周, start=2023-10-16, end=2023-10-22 },
    { week=第四周, start=2023-10-23, end=2023-10-29 },
    { week=第五周, start=2023-10-30, end=2023-11-05 }
]

你可能感兴趣的:(java,windows,开发语言)