0

how would i get the days of the week from a MonthCalendar?

if i select a day lets say. August 22,2013,

i would want a code that would get all the codes from Monday to sunday including August 22,2013.

that means i would get, aug 18,19,20,21,22,23,24,25.

so this is my solution but this is not what i want.

 List<DateTime> oneweek = new List<DateTime>();

 for (int i = 7; 0 <= i; i--)
 {
      oneweek.Add(mcCalendar.SelectionEnd.Subtract(new TimeSpan(i, 0, 0, 0)));
 }

it would get a list of dates from aug 22 and 7 days later.

like i said, i want the days of the week including august 22, from monday to sunday. aug 18,19,20,21,22,23,24,25.

Jeo Talavera
  • 527
  • 3
  • 8
  • 13
  • I know of no common notion of "week" that contains 8 days (especially one where you describe it as Monday to Saturday, which seems to exclude Sundays) and yet you twice give the example as 18,19,20,21,22,23,24,25? – Damien_The_Unbeliever Aug 22 '13 at 08:15

4 Answers4

0

you are using --i in your loop and then subtract in the statement

this hould work

for (int i = 0; i <= 7; i++)
{
   oneweek.Add(mcCalendar.SelectionEnd.Subtract(new TimeSpan(i, 0, 0, 0)));
}
0

You can get the start of the week using the method described in this answer

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 you would use like this:

DateTime monday = mcCalendar.SelectionEnd.StartOfWeek(DayOfWeek.Monday);
List<int> days = new List<int>();
for (int i = 0; i < 7; i++)
{
    days.Add(monday.AddDays(i).Day);
}
Community
  • 1
  • 1
shamp00
  • 11,106
  • 4
  • 38
  • 81
0

try to play with this .

  int i = 7 ; int j= 8 ; 
  for (int k = 0 ; k< 7 ;  k++ ) 
  { 

  DateTime dateValue = new DateTime(2008, i, j); // for example
  Console.WriteLine(dateValue.ToString("dddd"));    // Displays the day
  i++ ; j++ ; 
  }
Loubna H
  • 15
  • 7
0

You can just enumerate all dates within the week. Having a IEnumerable<DateTime> as a result, you can easily a collection you want - List, Array...

public static IEnumerable<DateTime> GetWeekDays(DateTime date, DayOfWeek start) {
  date = date.Date;

  int diff = date.DayOfWeek - start;

  if (diff < 0)
    diff += 7;

  for (int i = 0; i < 7; ++i)
    yield return date.AddDays(i - diff);
}

public static IEnumerable<DateTime> GetWeekDays(DateTime date) {
  return GetWeekDays(date, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek);
}

...

List<DateTime> oneWeek = GetWeekDays(DateTime.Now).ToList();
DateTime[] anotherWeek = GetWeekDays(new DateTime(2012, 5, 7)).ToArray();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215