I'm trying to write a method that will return a list of DateTimes representing a Monday-Sunday week. Its supposed to take the DateTime given to it and use it to calculate the surrounding dates
It calculates the starting date ok but the problem begins when it hits the last loop. With each run through the DateTime variable tmpDate should be incremented by 1 day, then added to the list. However, as it stands I'm getting back a List containing 7 starting dates.
Can anyone see where I'm going wrong (I have the feeling I may be made to look like a bit of a simpleton on this :) )?
Also, apologies if this is an often-asked question. Could see plenty of Start date/End Date and week number type questions, but none specifically dealing with this type of problem.private List<DateTime> getWeek(DateTime enteredDate)
{
/* Create List to hold the dates */
List<DateTime> week = new List<DateTime>();
int enteredDatePosition = (int)enteredDate.DayOfWeek;
/* Determine first day of the week */
int difference = 0;
for (int i = 0; i < 7; i++)
{
difference++;
if (i == enteredDatePosition)
{
break;
}
}
// 2 subtracted from difference so first and enteredDatePostion elements will not be counted.
difference -= 2;
DateTime startDate = enteredDate.Subtract(new TimeSpan(difference, 0, 0, 0));
week.Add(startDate);
/* Loop through length of a w开发者_开发百科eek, incrementing date & adding to list with each iteration */
DateTime tmpDate = startDate;
for (int i = 1; i < 7; i++)
{
tmpDate.Add(new TimeSpan(1, 0, 0, 0));
week.Add(tmpDate);
}
return week;
}
DateTime
s are immutable.
tmpDate.Add(...)
returns a new DateTime, and does not modify tmpDate
.
You should write tmpDate = tmpDate.AddDays(1)
or tmpDate += TimeSpan.FromDays(1)
I believe this snippet is tailored towards Sunday trough Saturday, but you can try something like this:
DateTime ToDate = DateTime.Now.AddDays((6 - (int)DateTime.Now.DayOfWeek) - 7);
DateTime FromDate = ToDate.AddDays(-6);
You're making your algorithm more complex than it needs to be. Check out this working snippet:
using System;
using System.Collections.Generic;
public class MyClass
{
public static void Main()
{
// client code with semi-arbitrary DateTime suuplied
List<DateTime> week = GetWeek(DateTime.Today.AddDays(-2));
foreach (DateTime dt in week) Console.WriteLine(dt);
}
public static List<DateTime> GetWeek(DateTime initDt)
{
// walk back from supplied date until we get Monday and make
// that the initial day
while (initDt.DayOfWeek != DayOfWeek.Monday)
initDt = initDt.AddDays(-1.0);
List<DateTime> week = new List<DateTime>();
// now enter the initial day into the collection and increment
// and repeat seven total times to get the full week
for (int i=0; i<7; i++)
{
week.Add(initDt);
initDt = initDt.AddDays(1.0);
}
return week;
}
}
精彩评论