获得C#月份第n个工作日 [英] get nth weekday of month in C#
本文介绍了获得C#月份第n个工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:结果
的如何确定给定的日期是每月的第N个工作日?
我如何获得这个月的第n个工作日?
How do i get the nth weekday of the month?
有关例:
2010年7月= 07/12/2010。
2nd Monday of "July 2010" = 07/12/2010.
在寻找的第二个星期一功能,如:
Looking for a function like:
public DateTime GetNthWeekofMonth(DateTime date, int nthWeek, DayOfWeek dayofWeek)
{
//return the date of nth week of month
}
从上面,所述的参数的第n周的日期该功能将(2010年7月的任何日期,2,星期一)
from the above, the parameters of the function will be ("Any Date in July 2010", 2, Monday).
推荐答案
使用下面的扩展方法:
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);
,或作为功能:
Or, as a function:
public DateTime GetNthWeekofMonth(DateTime date, int nthWeek, DayOfWeek dayOfWeek) {
return date.Next(dayOfWeek).AddDays((nthWeek - 1) * 7);
}
(我需要减去之一,因为 date.Next (星期几)
已经是当天的第一次出现)
(I need to subtract one because date.Next(dayOfWeek)
is already the first occurrence of that day)
这篇关于获得C#月份第n个工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文