我没有看到一个很好的方法来设置一个月的某一周的某一天的某一天的日期. 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;
}
Run Code Online (Sandbox Code Playgroud)
我个人不知道任何超级简单的方法,这是我用它来获得它:
/**
* 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);
}
Run Code Online (Sandbox Code Playgroud)
例:
System.out.println(nthWeekdayOfMonth(4, 1, 2012, 2));
Run Code Online (Sandbox Code Playgroud)
输出:
2012-01-12
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3630 次 |
最近记录: |