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

时间:2012-05-03 07:19:59

标签: c# datetime date

我需要检测如果当天是本季度最后一个月的第三个星期五

2012年将是这四个日期:

  • 2012-03-16
  • 2012-06-15
  • 2012年9月21日
  • 2012年12月21日

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

5 个答案:

答案 0 :(得分:2)

或者,你可以没有任何循环,只需假设今天是星期五,并找到它是2周前的那一天(应该是同一个星期五的积极匹配):

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

使用Bert Smith在This Answer中编写的扩展方法以下是方法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);

答案 3 :(得分:0)

您可以使用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

答案 4 :(得分:0)

// 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;
}