每月获得第三个星期五 [英] Get third friday of a month
问题描述
我正在为我的应用程序开发本地日历。
I am developing a local calendar for my application. but the is an issue with monthly repeat event (day of week).
当我创建从 2016年9月16日开始的事件时() 2016年9月16日(星期五)
,然后重复每个月的第三个星期五。但下个月它将在第二个
(2016年10月14日,星期五)创建(这是问题)。
When i am create an event starting on 16-9-2016(16 SEP 2016 FRIDAY)
and repeating Third Friday of each month. but next month it create on second
Friday 14-10-2016 (This is the issue). next month it will be on third Friday.
我的代码是
public Date nthWeekdayOfMonth(int dayOfWeek, int month, int year, int week, TimeZone timeZone) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(timeZone);
calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
calendar.set(Calendar.WEEK_OF_MONTH, week);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
return calendar.getTime();
}
我知道这个问题。但是我不知道如何解决它。.有什么方法可以解决它吗?
I know the issue. but i don`t know how to fix it.. is there any way to fix it ?
推荐答案
您的代码似乎是工作完全正常,据我所见,没有任何问题,可能是您的参数有误。
You code seems to be working completely fine, there is nothing that is going wrong from what I can see, it may be that your parameters are wrong.
请务必注意, MONTH
和 DAY
从0开始,因此, 0 =一月
和 0 =周日
,因此获取第三个星期五的参数应如下所示:
It is important to note that MONTH
and DAY
are 0-based so, 0 = January
and 0 = Sunday
so your parameters for getting the third friday should look like the following:
nthWeekdayOfMonth(6, 9, 2016, 3, TimeZone.getTimeZone("Europe/London"));
将返回以下输出:
Fri Oct 21 11:06:33 BST 2016
要打破下来:
- 星期几是6,因为星期日= 0。
- 月是9 -即10月
- 年份是正常的-2016
- 周不是基于0的,因此第3周将是索引3
- TimeZone正常
- Day of week is 6, because Sunday = 0.
- Month is 9 - i.e. October
- Year is normal - 2016
- Week is NOT 0-based so 3rd week will be index 3
- TimeZone as normal
请参见日历文档供参考。
因此出于某种原因,它在我的机器上可以工作,但不能在其他机器上工作;我不知道这可能是什么问题,但使用 DAY_OF_WEEK_IN_MONTH
似乎是一个更好的选择:
So for some reason, it works on my machine but it doesn't on others; I don't know what the issue could be with that but using DAY_OF_WEEK_IN_MONTH
seems to be a better option for this:
public static Date nthWeekdayOfMonth(int dayOfWeek, int month, int year, int week, TimeZone timeZone) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(timeZone);
calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
//calendar.set(Calendar.WEEK_OF_MONTH, week);
calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, week);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
return calendar.getTime();
}
我通常使用 GregorianCalendar
但 Calendar
应该可以正常工作。
I usually use GregorianCalendar
but Calendar
should work just fine.
(希望)该应该在大多数情况下都有效,我已经对其进行了测试在其他计算机上以及 ideone 上。
This should (hopefully) work for the most part, I've tested it on other machines and ideone.
这篇关于每月获得第三个星期五的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!