Created
November 30, 2022 18:26
-
-
Save chrcar01/ef7fe73e368a9b6cd49b98d4294f85e1 to your computer and use it in GitHub Desktop.
This file contains 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
/// <summary> | |
/// Helper for working with calendar concepts. | |
/// </summary> | |
public static class CalendarHelper | |
{ | |
/// <summary> | |
/// Returns all of the weeks for specified calendar month. | |
/// </summary> | |
public static IEnumerable<Week> GetWeeksForCalendarMonth(DateOnly month) | |
{ | |
var firstDayOfMonth = new DateOnly(month.Year, month.Month, 1); | |
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1); | |
var weeks = new List<Week>(); | |
for (int dayOfMonthIndex = 1; dayOfMonthIndex <= lastDayOfMonth.Day; dayOfMonthIndex++) | |
{ | |
var currentDate = new DateOnly(month.Year, month.Month, dayOfMonthIndex); | |
var days = new List<Day>(); | |
for (int dayOfWeek = 0; dayOfWeek <= 6; dayOfWeek++) | |
{ | |
var dayOfWeekOffset = dayOfWeek - (int)currentDate.DayOfWeek; | |
var dayDate = currentDate.AddDays(dayOfWeekOffset); | |
days.Add(new Day(dayDate)); | |
if (dayOfWeekOffset >= 0) | |
{ | |
dayOfMonthIndex++; | |
} | |
} | |
weeks.Add(new Week(days)); | |
} | |
return weeks; | |
} | |
} | |
public readonly record struct Week(List<Day> Days); | |
public readonly record struct Day(DateOnly Date); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment