Java获取指定时间一周至周日的日期:
public static List getWeekData(Date dataTime){ List week = new ArrayList(); Calendar calendar = Calendar.getInstance(); calendar.setTime(dataTime); // 如果是周日 if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { calendar.add(Calendar.DAY_OF_YEAR,-1); } // 获取当前日期是当周的第i天 int i = calendar.get(Calendar.DAY_OF_WEEK) - 1; // 获取当前日期所在周的第一天 calendar.add(Calendar.DATE , -i+1); LOGGER.info("日期所在周的周一是:" + new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime())); for (int j = 0; j < 7; j++) { if(j >0){ calendar.add(Calendar.DATE , 1); } week.add(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime())); } return week; }
测试类:
@org.junit.jupiter.api.Test void TestWeekUtil() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse("2023-07-11"); System.err.println(JSON.toJSON(DateHelper.getWeekData(date))); }
输出:
来源地址:https://blog.csdn.net/LookingTomorrow/article/details/131663267