Home >Backend Development >C++ >How to Get the Start of the Week (Sunday or Monday) in C#?
Calculating the Week's Start Date in C#
This article demonstrates how to easily find the beginning of the week (either Sunday or Monday) in C#, using the current date and time. We'll accomplish this using a concise extension method.
Extension Method Implementation:
<code class="language-csharp">public static class DateTimeExtensions { public static DateTime WeekStart(this DateTime dt, DayOfWeek firstDayOfWeek) { int dayDifference = (7 + (dt.DayOfWeek - firstDayOfWeek)) % 7; return dt.AddDays(-dayDifference).Date; } }</code>
Usage Examples:
The WeekStart
extension method simplifies the process of getting the week's start date. Here's how to use it:
<code class="language-csharp">DateTime mondayStart = DateTime.Now.WeekStart(DayOfWeek.Monday);</code>
<code class="language-csharp">DateTime sundayStart = DateTime.Now.WeekStart(DayOfWeek.Sunday);</code>
This approach offers a clean and efficient way to determine the start of the week, regardless of whether you define it as Sunday or Monday.
The above is the detailed content of How to Get the Start of the Week (Sunday or Monday) in C#?. For more information, please follow other related articles on the PHP Chinese website!