Skip to content

Instantly share code, notes, and snippets.

@codereflection
Created September 21, 2011 18:14
Show Gist options
  • Select an option

  • Save codereflection/1232851 to your computer and use it in GitHub Desktop.

Select an option

Save codereflection/1232851 to your computer and use it in GitHub Desktop.
Getting the last friday of the month as an extension method
public static class DateTimeExtensions
{
public static DateTime LastFridayOfMonth(this DateTime value)
{
var days = Enumerable.Range(1, DateTime.DaysInMonth(value.Year, value.Month));
var dates = days.Select(day => new DateTime(value.Year, value.Month, day));
var lastFriday = dates.OrderBy(day => day).Last(day => day.DayOfWeek == DayOfWeek.Friday);
return lastFriday;
}
}
@idavis

idavis commented Sep 21, 2011

Copy link
Copy Markdown
public static class DateTimeExtensions
{
    public static DateTime LastOfMonth(this DateTime value, DayOfWeek dayOfWeek)
    {
        var days = Enumerable.Range(1, DateTime.DaysInMonth(value.Year, value.Month));

        var dates = days.Select(day => new DateTime(value.Year, value.Month, day));

        var lastOfMonth = dates.Last(day => day.DayOfWeek == dayOfWeek);

        return lastOfMonth;
    }
}

@codereflection

Copy link
Copy Markdown
Author

Great idea.

@tt

tt commented Sep 21, 2011

Copy link
Copy Markdown

lastFriday may be somewhat misleading after the refactoring.

I would probably write it like this:

public static class DateTimeExtensions
{
    public static DateTime LastOfMonth(this DateTime value, DayOfWeek dayOfWeek)
    {
        var days = Enumerable.Range(1, DateTime.DaysInMonth(value.Year, value.Month))
            .Select(day => new DateTime(value.Year, value.Month, day))
            .Last(day => day.DayOfWeek == dayOfWeek);
    }
}

@idavis

idavis commented Sep 21, 2011

Copy link
Copy Markdown

Nice catch Troels, updated. I prefer to leave statements with ret vals. Easier to debug in the future if the need arises.

@tt

tt commented Sep 21, 2011

Copy link
Copy Markdown

An alternative approach would be:

public static class DateTimeExtensions
{
    public static DateTime LastOfMonth(this DateTime value, DayOfWeek dayOfWeek)
    {
        var days = Enumerable.Range(1, DateTime.DaysInMonth(value.Year, value.Month))
            .Select(day => new DateTime(value.Year, value.Month, day))
            .Where(day => day.DayOfWeek == dayOfWeek)
            .Max();
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment