HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How can I get the DateTime for the start of the week?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
datetimehowweektheforstartcanget

Problem

How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?

Something like:

DateTime.Now.StartWeek(Monday);

Solution

Use an extension method:

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
        return dt.AddDays(-1 * diff).Date;
    }
}


Which can be used as follows:

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);

Code Snippets

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
        return dt.AddDays(-1 * diff).Date;
    }
}
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);

Context

Stack Overflow Q#38039, score: 959

Revisions (0)

No revisions yet.