本文介绍了如何确定是否给定的日期是月的第N平日?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是什么,我试图做的:给定一个日期,星期几,和一个整数 N
,确定日期是否是 N
天时该月的
例如:
-
1/1/2009(星期一)输入,2
会是假的,因为1/1/2009
不是第二个星期一 到 -
输入
11/13/2008年,星期四2
将返回true,因为这是第二个星期四
如何才能改善这种实现?
私人布尔NthDayOfMonth(DateTime的日期,星期几道,INT N)
{
INT D = date.Day;
返回date.DayOfWeek ==道指和放大器;&安培; (D / 7 ==ñ||(D / 7 = =(N - 1)及和D%7 0));
}
解决方案
您可以改变一周的检查,以便该函数将改为:
私人布尔NthDayOfMonth(DateTime的日期,星期几道,INT N){
INT D = date.Day;
返回date.DayOfWeek ==道指和放大器;&安培; (D-1)/ 7 ==(N-1);
}
除此之外,它看起来pretty的良好和高效的。
Here is what I am trying to do:Given a date, a day of the week, and an integer n
, determine whether the date is the n
th day of the month.
For example:
input of
1/1/2009,Monday,2
would be false because1/1/2009
is not the second Mondayinput of
11/13/2008,Thursday,2
would return true because it is the second Thursday
How can I improve this implementation?
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n)
{
int d = date.Day;
return date.DayOfWeek == dow && (d/ 7 == n || (d/ 7 == (n - 1) && d % 7 > 0));
}
解决方案
You could change the check of the week so the function would read:
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){
int d = date.Day;
return date.DayOfWeek == dow && (d-1)/7 == (n-1);
}
Other than that, it looks pretty good and efficient.
这篇关于如何确定是否给定的日期是月的第N平日?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!