Home > Backend Development > C++ > How Do I Determine the Start of the Week (Monday or Sunday) in C#?

How Do I Determine the Start of the Week (Monday or Sunday) in C#?

Patricia Arquette
Release: 2025-01-22 14:01:10
Original
848 people have browsed it

How Do I Determine the Start of the Week (Monday or Sunday) in C#?

Determine the start date of the week (Monday or Sunday) in C#

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.

Start the week on Monday

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

How to use:

<code class="language-csharp">DateTime mondayStart = DateTime.Now.StartOfWeek();</code>
Copy after login

Start the week on Sunday

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

How to use:

<code class="language-csharp">DateTime sundayStart = DateTime.Now.StartOfWeek();</code>
Copy after login

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!

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