2

月の特定の週の特定の曜日に日付を設定する良い方法がわかりません。 Joda -TimeLocalDateには withWeekOfMonth メソッドがありません。可能性のあるアルゴリズムを見ることができますが、複雑に思えるので、何かが欠けていると仮定します。私が必要としているのは、誰かが支払われる次の日付を決定することです。また、月の第 2 木曜日に支払われる場合、それは何日ですか。

誰かがすでにこの問題を解決していますか?

わかりました、私はこれを思い付くことができました。これはうまくいくようです。

/**  
 * 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;  
}  
4

3 に答える 3

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
于 2012-10-23T15:19:47.723 に答える