C# offers several ways to identify the first day of the week, whether it's Sunday or Monday. A common task involves determining this based solely on the current date and time.
A flexible solution is to create a custom extension method that allows you to specify the desired starting day. This method uses modular arithmetic to calculate the difference between the current day and the specified start day:
<code class="language-csharp">public static class DateTimeExtensions { public static DateTime WeekStart(this DateTime dt, DayOfWeek startOfWeek) { int offset = (7 + (dt.DayOfWeek - startOfWeek)) % 7; return dt.AddDays(-offset).Date; } }</code>
This extension method is used like this:
<code class="language-csharp">DateTime mondayStart = DateTime.Now.WeekStart(DayOfWeek.Monday);</code>
This returns the date of the beginning of the week, starting on Monday. To find the start of the week beginning on Sunday:
<code class="language-csharp">DateTime sundayStart = DateTime.Now.WeekStart(DayOfWeek.Sunday);</code>
This approach provides a simple and efficient way to determine the week's starting date, regardless of the current day. This is particularly useful for tasks involving weekly scheduling or calculations.
The above is the detailed content of How Can I Determine the Start of the Week (Sunday or Monday) in C#?. For more information, please follow other related articles on the PHP Chinese website!