Friday, 24 August 2012

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

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);
 
 
ANS 
 
  
Using an extension method. They're the answer to everything you know! ;)
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;
    }
}
 
Which is used thusly:
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
 

No comments:

Post a Comment