How do I determine if a given date is the Nth weekday of the month?(如何确定给定日期是否是该月的第 N 个工作日?)
问题描述
这是我想要做的:给定日期、星期几和整数n
,判断日期是否是该月的第n
天.
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.
例如:
1/1/2009,Monday,2
的输入将是错误的,因为1/1/2009
不是第二个星期一
input of
1/1/2009,Monday,2
would be false because1/1/2009
is not the second Monday
输入2008 年 11 月 13 日,星期四,2
将返回 true,因为这是第二个星期四
input of
11/13/2008,Thursday,2
would return true because it is the second Thursday
如何改进这个实现?
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 个工作日?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何确定给定日期是否是该月的第 N 个工作日?


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01