Home > Backend Development > C++ > How Can I Get the Start of the Week in C#?

How Can I Get the Start of the Week in C#?

Mary-Kate Olsen
Release: 2025-01-22 14:13:09
Original
523 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template