检测该季度最后一个月中的第三个星期五



我需要检测当前日期是否是该季度最后一个月的第第三个星期五

对于2012年,这将是以下四个日期:

  • 2012年03月16
  • 2012年06月15
  • 2012年09月21
  • 2012年12月21

在 C# 中执行此操作的好方法是什么?

或者,您可以没有任何循环,简单地假设今天是第 3 个星期五,并找到 2 周前的哪一天(对于正匹配,应该是同月的星期五):

var now = DateTime.UtcNow;
var firstFriday = now.AddDays(-14);
return now.Month % 3 == 0
    && firstFriday.DayOfWeek == DaysOfWeek.Friday
    && now.Month == firstFriday.Month;

好吧,你可以从那个月的第一天开始,一直前进到找到第一个星期五,发布你可以增加 14 天到达第三个星期五

使用伯特·史密斯(Bert Smith)在此答案中编写的扩展方法 这是方法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);

可以使用 .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;
}

最新更新