Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datetime

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);
like image 850
GateKiller Avatar asked Sep 01 '08 15:09

GateKiller


4 Answers

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);
like image 145
Compile This Avatar answered Nov 13 '22 23:11

Compile This


The quickest way I can come up with is:

var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);

If you would like any other day of the week to be your start date, all you need to do is add the DayOfWeek value to the end

var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday);

var tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday);
like image 32
Eric Avatar answered Nov 14 '22 00:11

Eric


A little more verbose and culture-aware:

System.Globalization.CultureInfo ci = 
    System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
DayOfWeek today = DateTime.Now.DayOfWeek;
DateTime sow = DateTime.Now.AddDays(-(today - fdow)).Date;
like image 76
Jason Navarrete Avatar answered Nov 13 '22 22:11

Jason Navarrete


Using Fluent DateTime:

var monday = DateTime.Now.Previous(DayOfWeek.Monday);
var sunday = DateTime.Now.Previous(DayOfWeek.Sunday);
like image 41
Simon Avatar answered Nov 14 '22 00:11

Simon