记录一下Java获取指定日期的第一个周一的方法实现
public Date getFirstMonday(Date date) throws ParseException {
Date firstMonday = null;
Calendar c = Calendar.getInstance();
c.setTime(date);
Integer year = c.get(Calendar.YEAR);
Integer month = c.get(Calendar.MONTH) + 1;
c.set(year, month - 1, 1);
int mountDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd E");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (int i=1;i<=mountDay;i++) {
String date1 = year + "-";
if (month < 10) {
date1 += "0" + month + "-";
} else {
date1 += month + "-";
}
if (i < 10) {
date1 += "0" + i;
} else {
date1 += i;
}
String dateStr = sim.format(sdf.parse(date1));
String weekStr = dateStr.substring(11,13);
if ("周一".equals(weekStr)) {
firstMonday = sdf.parse(date1);
break;
}
}
return firstMonday;
}
该方法使用Java的Calendar类和SimpleDateFormat类,通过遍历指定日期所在月份的每一天,判断是否为周一,找到第一个周一并返回其日期对象。
1998

被折叠的 条评论
为什么被折叠?



