In C#, determining the start date of the week is useful for various scenarios such as scheduling or data aggregation. To achieve this we need to consider the definition of the start of the week, which may vary depending on the specific engagement or region.
For regions that start the week on Monday, we can use the extension method:
<code class="language-csharp">public static class DateTimeExtensions { public static DateTime StartOfWeek(this DateTime dt) { int diff = dt.DayOfWeek - DayOfWeek.Monday; return dt.AddDays(-diff).Date; } }</code>
How to use:
<code class="language-csharp">DateTime mondayStart = DateTime.Now.StartOfWeek();</code>
For regions that start the week on Sunday, we can modify the extension method slightly:
<code class="language-csharp">public static class DateTimeExtensions { public static DateTime StartOfWeek(this DateTime dt) { int diff = dt.DayOfWeek - DayOfWeek.Sunday; return dt.AddDays(-diff).Date; } }</code>
How to use:
<code class="language-csharp">DateTime sundayStart = DateTime.Now.StartOfWeek();</code>
These extension methods provide a flexible and customizable way to determine the start date of the week based on the desired convention.
The above is the detailed content of How Do I Determine the Start of the Week (Monday or Sunday) in C#?. For more information, please follow other related articles on the PHP Chinese website!