Home > Backend Development > C++ > How to Get the Start of the Week (Sunday or Monday) in C#?

How to Get the Start of the Week (Sunday or Monday) in C#?

DDD
Release: 2025-01-22 14:06:12
Original
433 people have browsed it

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

Usage Examples:

The WeekStart extension method simplifies the process of getting the week's start date. Here's how to use it:

  • Monday as the first day:
<code class="language-csharp">DateTime mondayStart = DateTime.Now.WeekStart(DayOfWeek.Monday);</code>
Copy after login
  • Sunday as the first day:
<code class="language-csharp">DateTime sundayStart = DateTime.Now.WeekStart(DayOfWeek.Sunday);</code>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template