这是一个很酷的问题,这是我想出的解决方案和我的方法:
首先你有什么:
public static void main(String[] args) {
// TODO: validate user-input
// Input by user:
int inputDayOfWeek = 3; // Tuesday
int inputWeekOfMonth = 2;
if(isInNextMonth(inputDayOfWeek, inputWeekOfMonth)){
Date outputDate = calculateNextValidDate(inputDayOfWeek, inputWeekOfMonth);
// Do something with the outputDate
System.out.println(outputDate.toString());
}
}
private static boolean isInNextMonth(int inputDayOfWeek, int inputWeekOfMonth){
// Current day:
Calendar cal = Calendar.getInstance();
int currentDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int currentWeekOfMonth = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
// The date has gone past in the current month
// OR though it's the same week of the month, the day of the week is past the current day of the week
return inputWeekOfMonth < currentWeekOfMonth || ((inputWeekOfMonth == currentWeekOfMonth) && inputDayOfWeek < currentDayOfWeek);
}
需要注意的一点:我将 if 和 if-else 都放在了一个 if 中,因为在这两种情况下你都想去下个月,并且还把它变成了一个单独的方法(使它成为一个单独的方法只是我自己的偏好,以保持事物的结构和组织)。
我注意到的另一件事是您的 if 和 else-if 中有一个错误。应该是 noOfWeek < currentNoOfWeek 而不是 noOfWeek > currentNoOfWeek 和 ((noOfWeek == currentNoOfWeek) && dayOfWeek > currentDayOfWeek) 而不是 ((noOfWeek == currentNoOfWeek) && dayOfWeek < currentDayOfWeek)(< 和 > 是相反的)。
现在是 calculateNextValidDate 方法,这是您的问题所在。我的做法如下:
- 从下个月的第一天开始
- 转到本月的正确周
- 然后转到本周的正确日期
这给了我以下代码:
private static Date calculateNextValidDate(int inputDayOfWeek, int inputWeekOfMonth){
// Set the first day of the next month as starting position:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
// Now first go to the correct week of this month
int weekOfNextMonth = 1;
while(weekOfNextMonth < inputWeekOfMonth){
// Raise by a week
cal.add(Calendar.DAY_OF_MONTH, 7);
weekOfNextMonth++;
}
// Now that we have the correct week of this month,
// we get the correct day
while(cal.get(Calendar.DAY_OF_WEEK) != inputDayOfWeek){
// Raise by a day
cal.add(Calendar.DAY_OF_MONTH, 1);
}
return cal.getTime();
}
这段代码给了我以下输出(在 2014 年 11 月 5 日星期三 - 以 3 [Tuesday] 和 2 作为输入):
Tue Dec 09 17:05:42 CET 2014
还请注意我在本文第一个代码部分的主方法中添加的// TODO:。如果用户输入无效(例如负周或 dayOfMonth),它可能会通过 while 循环太多次。我让你来验证用户输入。