Joda-Time-如何查找“本月第二个星期四" [英] Joda-Time - How to find "Second Thursday of Month"

查看:50
本文介绍了Joda-Time-如何查找“本月第二个星期四"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看不到将日期设置为某月某周中某天的好方法. Joda-Time

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

推荐答案

我个人不知道这样做的任何超级简单方法,这就是我用来获取它的方法:

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

示例:

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

输出:

2012-01-12

这篇关于Joda-Time-如何查找“本月第二个星期四"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆