現在の日が四半期の最後の月の第 3 金曜日であるかどうかを検出する必要があります。
2012 年の場合、次の 4 つの日付になります。
- 2012-03-16
- 2012-06-15
- 2012-09-21
- 2012-12-21
C#でこれを行う良い方法は何ですか?
この回答でBertSmithによって書かれた拡張メソッドを使用するこれIsThirdFridayInLastMonthOfQuarter
があなたが探しているものを正確に実行するメソッドです:
public static class DateHelper
{
public static DateTime NthOf(this DateTime CurDate, int Occurrence, DayOfWeek Day)
{
var fday = new DateTime(CurDate.Year, CurDate.Month, 1);
var fOc = fday.DayOfWeek == Day ? fday : fday.AddDays(Day - fday.DayOfWeek);
// CurDate = 2011.10.1 Occurance = 1, Day = Friday >> 2011.09.30 FIX.
if (fOc.Month < CurDate.Month) Occurrence = Occurrence + 1;
return fOc.AddDays(7 * (Occurrence - 1));
}
public static bool IsThirdFridayInLastMonthOfQuarter(DateTime date)
{
// quarter ends
int[] months = new int[] { 3, 6, 9, 12 };
// if the date is not in the targeted months, return false.
if (!months.Contains(date.Month))
return false;
// get the date of third friday in month
DateTime thirdFriday = date.NthOf(3, DayOfWeek.Friday);
// check if the date matches and return boolean
return date.Date == thirdFriday.Date;
}
}
それを使用するには:
bool isThirdFriday = DateHelper.IsThirdFridayInLastMonthOfQuarter(date);
Time Period Library for .NETを使用できます。
// ----------------------------------------------------------------------
public DateTime? GetDayOfLastQuarterMonth( DayOfWeek dayOfWeek, int count )
{
Quarter quarter = new Quarter();
Month lastMonthOfQuarter = new Month( quarter.End.Date );
DateTime? searchDay = null;
foreach ( Day day in lastMonthOfQuarter.GetDays() )
{
if ( day.DayOfWeek == dayOfWeek )
{
count--;
if ( count == 0 )
{
searchDay = day.Start.Date;
break;
}
}
}
return searchDay;
} // GetDayOfLastQuarterMonth
次に、チェックを行います。
// ----------------------------------------------------------------------
public void CheckDayOfLastQuarterMonth()
{
DateTime? day = GetDayOfLastQuarterMonth( DayOfWeek.Friday, 3 );
if ( day.HasValue && day.Equals( DateTime.Now.Date ) )
{
// do ...
}
} // CheckDayOfLastQuarterMonth
// Do a few cheap checks and ensure that current month is the last month of
// quarter before computing the third friday of month
if (Cur.DayOfWeek == DayOfWeek.Friday && Cur.Day > 14 && Cur.Month % 3 == 0) {
var Friday = new DateTime(Cur.Year, Cur.Month, 15);
Friday = Friday.AddDays((5 - (int)Friday.DayOfWeek + 7) % 7);
if (Cur.Day == Friday.Day)
return true;
}