Home >Backend Development >C++ >How Can I Get the Start of the Week in C#?
Calculating the Week's Start Date in C#
Many programming tasks require identifying the start of a week. While C# doesn't offer a built-in function for this, we can easily create one using an extension method.
Extension methods enhance existing classes without altering their original code. We'll define our extension method within a static class to extend the DateTime
class:
<code class="language-csharp">public static class DateTimeExtensions { public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek = DayOfWeek.Monday) { int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7; return dt.AddDays(-1 * diff).Date; } }</code>
The StartOfWeek
method generates a new DateTime
object representing the week's beginning, based on the provided startOfWeek
parameter. The default is Monday. To use Sunday as the start, pass DayOfWeek.Sunday
as an argument.
Using the extension method is straightforward:
<code class="language-csharp">DateTime dt = DateTime.Now.StartOfWeek(); // Defaults to Monday</code>
This returns the start of the current week (Monday). To begin the week on Sunday:
<code class="language-csharp">DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);</code>
The above is the detailed content of How Can I Get the Start of the Week in C#?. For more information, please follow other related articles on the PHP Chinese website!