我没有看到一个很好的方法来设置一个月的某个星期的某一天的某一天的日期。 Joda-Time的LocalDate没有withWeekOfMonth方法。我可以看到一个可能的算法,但它看起来很复杂,所以我会假设我错过了一些东西。我需要的是确定某人付款的下一个日期。如果他们在本月的第二个星期四付款,那是什么日期。
有人已经解决了这个问题吗?
好的,我能够想出这个,看起来效果很好。
/**
* Finds a date such as 2nd Tuesday of a month.
*/
public static LocalDate calcDayOfWeekOfMonth( final DayOfWeek pDayOfWeek, final int pWeekOfMonth, final LocalDate pStartDate )
{
LocalDate result = pStartDate;
int month = result.getMonthOfYear();
result = result.withDayOfMonth( 1 );
result = result.withDayOfWeek( pDayOfWeek.ordinal() );
if ( result.getMonthOfYear() != month )
{
result = result.plusWeeks( 1 );
}
result = result.plusWeeks( pWeekOfMonth - 1 );
return result;
}
答案 0 :(得分:7)
我个人不知道有什么超级简单的做法,这就是我用它来获取它:
/**
* Calculates the nth occurrence of a day of the week, for a given month and
* year.
*
* @param dayOfWeek
* The day of the week to calculate the day for (In the range of
* [1,7], where 1 is Monday.
* @param month
* The month to calculate the day for.
* @param year
* The year to calculate the day for.
* @param n
* The occurrence of the weekday to calculate. (ie. 1st, 2nd,
* 3rd)
* @return A {@link LocalDate} with the nth occurrence of the day of week,
* for the given month and year.
*/
public static LocalDate nthWeekdayOfMonth(int dayOfWeek, int month, int year, int n) {
LocalDate start = new LocalDate(year, month, 1);
LocalDate date = start.withDayOfWeek(dayOfWeek);
return (date.isBefore(start)) ? date.plusWeeks(n) : date.plusWeeks(n - 1);
}
示例:
System.out.println(nthWeekdayOfMonth(4, 1, 2012, 2));
输出:
2012-01-12