Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate 2nd Friday of Month in C# [duplicate]

Possible Duplicate:
How to find the 3rd Friday in a month with C#?

Hi everyone,

I've wrote a little console utility that spits out a line into a text file. I want this line to include the second Friday of the current month. Is there any way to do this?

Thanks everyone!

like image 416
New Start Avatar asked May 26 '11 14:05

New Start


2 Answers

Slight variation on @druttka: using an extension method.

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

Then called it like this:

 for (int i = 1; i < 13; i++)
 {
      Console.WriteLine(new DateTime(2011, i,1).NthOf(2, DayOfWeek.Friday));
 }
like image 172
Bert Smith Avatar answered Oct 18 '22 10:10

Bert Smith


I would go for something like this.

    public static DateTime SecondFriday(DateTime currentMonth)
    {
        var day = new DateTime(currentMonth.Year, currentMonth.Month, 1);
        day = FindNext(DayOfWeek.Friday, day);
        day = FindNext(DayOfWeek.Friday, day.AddDays(1));
        return day;
    }

    private static DateTime FindNext(DayOfWeek dayOfWeek, DateTime after)
    {
        DateTime day = after;
        while (day.DayOfWeek != dayOfWeek) day = day.AddDays(1);
        return day;
    }
like image 43
vidstige Avatar answered Oct 18 '22 09:10

vidstige