我正在尝试编写一个方法,该方法将返回表示周一至周日周的DateTimes列表。它应该采用DateTime给它并用它来计算周围的日期
它计算开始日期ok,但问题在它到达最后一个循环时开始。每次运行DateTime变量时,tmpDate应增加1天,然后添加到列表中。但是,就目前而言,我正在找回一个包含7个开始日期的列表。
任何人都可以看到我出错的地方(我觉得我可能看起来有点像这样的简单:)) 此外,如果这是一个经常被问到的问题,请道歉。可以看到大量的开始日期/结束日期和周数类型问题,但没有专门处理此类问题。
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 week, 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;
}
答案 0 :(得分:4)
DateTime
是不可变的
tmpDate.Add(...)
返回新的DateTime,不会修改tmpDate
。
您应该写tmpDate = tmpDate.AddDays(1)
或tmpDate += TimeSpan.FromDays(1)
答案 1 :(得分:1)
我相信这个片段是针对星期六的星期六,但你可以尝试这样的事情:
DateTime ToDate = DateTime.Now.AddDays((6 - (int)DateTime.Now.DayOfWeek) - 7);
DateTime FromDate = ToDate.AddDays(-6);
答案 2 :(得分:1)
你使你的算法比它需要的更复杂。看看这个工作片段:
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;
}
}