Skip to content

Instantly share code, notes, and snippets.

@mikeminutillo
Last active December 10, 2015 14:39
Show Gist options
  • Save mikeminutillo/4449454 to your computer and use it in GitHub Desktop.
Save mikeminutillo/4449454 to your computer and use it in GitHub Desktop.
A way to generate the dates that need to appear on a calendar page
void Main()
{
var refDate = DateTime.Today.AddMonths(-1);
var start = refDate.StartOfMonth().Backwards().FirstOrDefault (d => d.DayOfWeek == DayOfWeek.Monday);
var end = refDate.EndOfMonth().Forwards().FirstOrDefault (d => d.DayOfWeek == DayOfWeek.Sunday);
start.UpTo(end).ToArray().Dump();
}
public static class Ext
{
public static DateTime StartOfMonth(this DateTime refDate)
{
return new DateTime(refDate.Year, refDate.Month, 1);
}
public static DateTime EndOfMonth(this DateTime refDate)
{
return refDate.AddMonths(1).StartOfMonth().AddDays(-1);
}
public static IEnumerable<DateTime> UpTo(this DateTime start, DateTime end)
{
return start.Forwards().TakeWhile(x => x <= end);
}
public static IEnumerable<DateTime> Forwards(this DateTime start)
{
return start.Generate(x => x.AddDays(1));
}
public static IEnumerable<DateTime> Backwards(this DateTime start)
{
return start.Generate(x => x.AddDays(-1));
}
public static IEnumerable<T> Generate<T>(this T start, Func<T, T> getNext)
{
var current = start;
while(true)
{
yield return current;
current = getNext(current);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment