c# - 在 C# 中获取一个月的第 n 个工作日

标签 c# date dayofweek

<分区>

Possible Duplicate:
How do I determine if a given date is Nth weekday of the month?

我如何获得该月的第 n 个工作日?

例如:

“2010 年 7 月”的第二个星期一 = 07/12/2010。

寻找像这样的函数:

public DateTime GetNthWeekofMonth(DateTime date, int nthWeek, DayOfWeek dayofWeek)
{
//return the date of nth week of month
}

从上面可以看出,该函数的参数将为(“2010 年 7 月的任何日期”,2,星期一)。

最佳答案

使用以下扩展方法:

public static class DateTimeExtensions
{
    ///<summary>Gets the first week day following a date.</summary>
    ///<param name="date">The date.</param>
    ///<param name="dayOfWeek">The day of week to return.</param>
    ///<returns>The first dayOfWeek day following date, or date if it is on dayOfWeek.</returns>
    public static DateTime Next(this DateTime date, DayOfWeek dayOfWeek) { 
        return date.AddDays((dayOfWeek < date.DayOfWeek ? 7 : 0) + dayOfWeek - date.DayOfWeek); 
    }
}

然后你可以写

new DateTime(2010, 07, 01).Next(DayOfWeek.Monday).AddDays((2 - 1) * 7);

或者,作为一个函数:

public DateTime GetNthWeekofMonth(DateTime date, int nthWeek, DayOfWeek dayOfWeek) {
    return date.Next(dayOfWeek).AddDays((nthWeek - 1) * 7);
}

(我需要减去一个,因为 date.Next(dayOfWeek) 已经是那天的第一次出现)

关于c# - 在 C# 中获取一个月的第 n 个工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3284452/

相关文章:

c# 删除我的 case 语句中的重复项。使 Case 语句动态化

php - strtotime 可以返回给定日期之后一天的日期和时间吗?

python - 使用日期格式设置 X 轴格式

JavaScript:将日/周转换为年

Java 8 LocalDate : Determine What Monday of the Month its (1st, 第二、第三等)

c# - LINQ,仅选择子项的第一个元素

c# - 从 P/Invoke 捕获 DllNotFoundException

mysql - 返回到输入日期 MySQL 的月初

apache-flex - 查找去年一周中同一天的日期?

c# - DNN 6 在登录页面隐藏找回密码