Skip to content

Instantly share code, notes, and snippets.

@yozawiratama
Last active February 10, 2023 10:51
Show Gist options
  • Save yozawiratama/5467256537b31f6617c9e49398c0ea88 to your computer and use it in GitHub Desktop.
Save yozawiratama/5467256537b31f6617c9e49398c0ea88 to your computer and use it in GitHub Desktop.
C# .Net Get First and Last Date in a specific Week
static List<DateTime> FirstLastDayInWeek(int Year, int month, int WeekNumber)
{
WeekNumber -= 1;
DateTime start = new DateTime(Year, month, 1).AddDays(7 * WeekNumber);
start = start.AddDays(-((int)start.DayOfWeek));
return Enumerable.Range(0, 7).Select(num => start.AddDays(num)).ToList()
.Where(w => w.Year == Year && w.Month == month).ToList();
}
// to use it
List<DateTime> dates = FirstLastDayInWeek(2022, 2, 1).ToList();
Console.WriteLine($"First: {dates.First().ToString("yyyy-MM-dd")}");
Console.WriteLine($"Last: {dates.Last().ToString("yyyy-MM-dd")}");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment