Thursday, March 22, 2012

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

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);

No comments:

Post a Comment

Don't judge me like you know me.Don't talk to me if you don't like me. I am my own person and If you don't like that i don't give a f***