我有c#asp.net应用程序。 我想计算之前的16个今日,而给出当前的日期,它将给出16个最后的那个日期。
请提供此示例代码。
感谢上的感谢。
答案 0 :(得分:0)
此方法有效:
public static IList<DateTime> GetWeekDays(DateTime startDate, DayOfWeek day, int count, bool pastDays, bool includeStartDate)
{
int start = (int)startDate.DayOfWeek;
int desired = (int)day;
int offset;
int diff = Math.Abs(start - desired);
if(!includeStartDate && start == desired)
diff = 7;
offset = pastDays ? (-1) * (7- diff) : diff;
int weekDays = pastDays ? (-1) * 7 : 7;
DateTime firstDay = startDate.AddDays(offset);
IList<DateTime> dates = Enumerable.Range(0, count)
.Select(i => firstDay.AddDays(i * weekDays))
.ToList();
return dates;
}
它支持两个方向。
用法很简单:
IList<DateTime> past16Wednesdays = GetWeekDays(DateTime.Today, DayOfWeek.Wednesday, 16, true, true);
foreach(DateTime dt in past16Wednesdays)
Console.WriteLine(dt.ToString("d", CultureInfo.InvariantCulture));
结果是
11/20/2013
11/13/2013
11/06/2013
10/30/2013
10/23/2013
10/16/2013
10/09/2013
10/02/2013
09/25/2013
09/18/2013
09/11/2013
09/04/2013
08/28/2013
08/21/2013
08/14/2013
08/07/2013