Created
September 21, 2011 18:14
-
-
Save codereflection/1232851 to your computer and use it in GitHub Desktop.
Getting the last friday of the month as an extension method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
commented
Sep 21, 2011
Author
Great idea.
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);
}
}
Nice catch Troels, updated. I prefer to leave statements with ret vals. Easier to debug in the future if the need arises.
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