2011/01/21

DateTime: Get the first date of the week

1. Create an 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;
    }
}
2. The way to use.
//if your first day is set to Sunday
Console.WriteLine(DateTime.Now.StartOfWeek(DayOfWeek.Sunday));
//if your first day is set to Monday
Console.WriteLine(DateTime.Now.StartOfWeek(DayOfWeek.Monday));
The output is
1/16/2011 12:00:00 AM
1/17/2011 12:00:00 AM
You can change the DateTime.Now to any date.

No comments:

Post a Comment