Java实现:获取从当前日期起指定星期几的最后日期
获取从当前日期开始的指定星期几的最近日期
嘿,我来帮你搞定这个需求!先明确一下:你想要的是从当前日期开始,找到往后最近的指定星期几的日期——比如今天是2018年3月5日(周一),如果指定周五,结果就是3月9日;如果指定周日,结果就是3月11日(因为本周日已经过去了)。对吧?
基于Calendar的实现(适配你现有的函数)
你已经有了字符串转Calendar dayOfWeek的函数,那我们直接基于Calendar来实现目标方法:
首先,先确认你那字符串转dayOfWeek的函数大概是这样的(如果不是可以调整):
public static int convertToCalendarDayOfWeek(String weekdayStr) { switch (weekdayStr.toUpperCase()) { case "SUNDAY": return Calendar.SUNDAY; case "MONDAY": return Calendar.MONDAY; case "TUESDAY": return Calendar.TUESDAY; case "WEDNESDAY": return Calendar.WEDNESDAY; case "THURSDAY": return Calendar.THURSDAY; case "FRIDAY": return Calendar.FRIDAY; case "SATURDAY": return Calendar.SATURDAY; default: throw new IllegalArgumentException("无效的星期字符串: " + weekdayStr); } }
然后是核心的目标方法:
import java.util.Calendar; import java.util.Date; public static Date getLastSpecifiedWeekdayFromCurrent(Date currentDate, int targetDayOfWeek) { // 先校验目标星期几的合法性 if (targetDayOfWeek < Calendar.SUNDAY || targetDayOfWeek > Calendar.SATURDAY) { throw new IllegalArgumentException("无效的目标星期几数值: " + targetDayOfWeek); } Calendar cal = Calendar.getInstance(); cal.setTime(currentDate); int currentDay = cal.get(Calendar.DAY_OF_WEEK); int daysToAdd; if (currentDay == targetDayOfWeek) { // 如果今天就是目标星期几,直接返回当天 daysToAdd = 0; } else if (currentDay < targetDayOfWeek) { // 当前星期在目标之前,直接算差值 daysToAdd = targetDayOfWeek - currentDay; } else { // 当前星期在目标之后,需要跨到下周 daysToAdd = (7 - currentDay) + targetDayOfWeek; } cal.add(Calendar.DAY_OF_MONTH, daysToAdd); return cal.getTime(); }
更简洁的Java 8+ LocalDate实现
如果你用的是Java 8及以上,强烈推荐用LocalDate,代码更清晰易读:
import java.time.DayOfWeek; import java.time.LocalDate; public static LocalDate getLastSpecifiedWeekdayFromCurrent(LocalDate currentDate, DayOfWeek targetDayOfWeek) { LocalDate targetDate = currentDate.with(targetDayOfWeek); // 如果目标日期在当前日期之前,就往后推一周 return targetDate.isBefore(currentDate) ? targetDate.plusWeeks(1) : targetDate; }
测试示例
比如你说的场景:当前日期是2018年3月5日(周一)
- 找周五:两种方法都会返回
2018-03-09 - 找周日:两种方法都会返回
2018-03-11 - 找周一:直接返回当天
2018-03-05
内容的提问来源于stack exchange,提问作者LAP0109




