如果我正在编写一些贯穿一年日期(按天迭代)的 C# 代码,并且希望每个月的第三个星期一发生一些特别的事情,我该如何实现呢?
换句话说,找出当前星期一是一个月中哪个星期一的最佳方法是什么?
public bool IsThirdMondayOfMonth(DateTime dt)
{
if(dt.DayOfWeek == DayOfWeek.Monday && dt.Day > 14 && dt.Day <= 21)
{
return true;
}
return false;
}
I don't think your "in other words" really restates the problem that you describe first, so I'll answer both.
Here's a fairly simple method that will determine the nth occurrence of a particular day of the week in a given month in a given year.
public static DateTime DayOccurrence(int year, int month, DayOfWeek day,
int occurrenceNumber)
{
DateTime start = new DateTime(year, month, 1);
DateTime first = start.AddDays((7 - ((int)start.DayOfWeek - (int)day)) % 7);
return first.AddDays(7 * (occurrenceNumber - 1));
}
Determining which Monday (or any other day) of the month a date is is much easier; just take the ceiling of the day of the month / 7:
public static int DayOccurrence(DateTime date)
{
return (int)Math.Ceiling(date.Day / 7.0);
}
Find the Monday that is between the 15th and the 21st, inclusive.
I don't know if there is a date manipulation library to do what you want, but you can write your own functions pretty easily:
using System;
class Program {
static void Main(string[] args) {
int year = 2010;
int month = 05;
DateTime thirdMonday = ThirdMonday(year, month);
}
private static DateTime ThirdMonday(int year, int month) {
for (int day = 1; day <= DateTime.DaysInMonth(year, month); ++day) {
DateTime dt = new DateTime(year, month, day);
if (dt.DayOfWeek == DayOfWeek.Monday) {
return dt.AddDays(14);
}
}
// this should never happen
throw new Exception();
}
}