4

Suppose my input is March 31, 2015.
How would I be able to get the days of the week that March 31, 2015 is in?
In this case, it should output:
March 29, 2015-April 4, 2015

I found something similar here but it's not quite what I'm looking for as that one takes in the week number while my input is a date itself.

Community
  • 1
  • 1
Katie
  • 357
  • 1
  • 12
  • Oops! You're right! Fixed! – Katie Mar 31 '15 at 18:47
  • When do you consider the start of the week to be? – Servy Mar 31 '15 at 18:47
  • One thing you can do is get the week number with the [`DayOfYear`](https://msdn.microsoft.com/en-us/library/system.datetime.dayofyear(v=vs.110).aspx) `/ 7` then use that solution. – ryanyuyu Mar 31 '15 at 18:47
  • 1
    Perhaps check the `Date.getDay` method, and subtract X from Mar 31st until you get Sunday, then add Y until you get to Saturday? – sab669 Mar 31 '15 at 18:47

3 Answers3

7
DateTime date = new DateTime(2015, 3, 31);
DateTime weekFirstDay = date.AddDays(DayOfWeek.Sunday - date.DayOfWeek);
DateTime weekLastDay = weekFirstDay.AddDays(6);
Ulugbek Umirov
  • 12,719
  • 3
  • 23
  • 31
4

Here is a way to get each value separately from a given DateTime

Week start:

    public static DateTime GetWeekStartDate(DateTime value)
    {
        return value.AddDays(-(int)value.DayOfWeek).Date;
    }

Week end:

    public static DateTime GetWeekEndDate(DateTime value)
    {
        return value.AddDays(6 - (int)value.DayOfWeek).Date;
    }
Jeffrey Wieder
  • 2,336
  • 1
  • 14
  • 12
2
DayOfWeek firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
DateTime startDate = DateTime.Now;

while (firstDayOfWeek != startDate.DayOfWeek)
{
   startDate = startDate.AddDays(-1);
}

DateTime firstDay = startDate.Date;
DateTime lastDay = startDate.AddDays(6);
puko
  • 2,819
  • 4
  • 18
  • 27