Home > C# Snippets > C#: Get the first date of week for specified date

C#: Get the first date of week for specified date

16:51

Marek Śliwiński Leave a comment Print This Post  (914) Go to comments

Source:
http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week

If you have similiar solution than test it for 2009-02-01 (sunday) date (yyyy-mm-dd). Correct result should be 2009-01-26.

Extension method:

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
                diff += 7;
        }

        return dt.AddDays(-1 * diff).Date;
    }
}

Example of use

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
Share and Enjoy:
  • DotNetKicks
  • Digg
  • del.icio.us
  • Wikio IT
  • Google Bookmarks
  • Facebook
  • Print
Categories: C# Snippets Tags:
  1. No comments yet.
  1. No trackbacks yet.

Subscribe without commenting