根据年和第几周来获取对应的日期区间(自己用最笨的代码写的,如有更简单的方法,请网友评论区写一下谢谢)

public static void main(String[] args) {
//根据年和第几周来获取对应的日期区间
System.out.println(getWeekDays(2021,1));//2021-01-01至2021-01-04


}

public static String getWeekDays(Integer year, Integer week) {
if (week==1) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
cal.add(Calendar.DAY_OF_WEEK, 6);
String endDate = sdf.format(cal.getTime());
return year+"-01-01" + "至" + endDate;
}
if (week==53) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
String beginDate = sdf.format(cal.getTime());
cal.add(Calendar.DAY_OF_WEEK, 6);
return beginDate + "至" + year+"-12-31";
}


SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
String beginDate = sdf.format(cal.getTime());
cal.add(Calendar.DAY_OF_WEEK, 6);
String endDate = sdf.format(cal.getTime());
return beginDate + "至" + endDate;
}

posted @ 2021-04-20 15:56  小玲子丫  阅读(172)  评论(0编辑  收藏  举报