Joda-Time - How to find “Second Thursday of Month”

一世执手 提交于 2019-12-22 10:45:39

问题


I'm not seeing a good way to set a date to a certain day of the week for a certain week of the month. Joda-Time's LocalDate does not have a withWeekOfMonth method. I can see a possible algorithm, but it seems way to complicated, so I'm going to assume I'm missing something. What I need is to determine the next date someone is paid. And if they are paid on the Second Thursday of the Month, what date is that.

Anyone already solved this problem?

Ok, I was able to come up with this, which seems to work fine.

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

回答1:


I personally don't know of any super-simple way of doing it, this is what I use to get it:

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

Example:

System.out.println(nthWeekdayOfMonth(4, 1, 2012, 2));

Output:

2012-01-12


来源:https://stackoverflow.com/questions/13033167/joda-time-how-to-find-second-thursday-of-month

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!