任何人请每两周用C#MVC 5日历逻辑帮助我。我已经实施了每周日期。
这是我的每周代码。它正在发挥作用。
var day = (from o in db.Suburbs.AsEnumerable()
..etc
select new
{
DT.DeliveryDay,
}).ToList();
foreach (var temp in day)
{
if (Type == "weekly")
{
int weeklyLogic = ((int)Enum.Parse(typeof(DayOfWeek), temp.DeliveryDay) - (int)today.DayOfWeek + 7) % 7;
DateTime nextweeklyLogic = today.AddDays(weeklyLogic);
Firstweek = nextweeklyLogic;
int weekly2 = (((int)Enum.Parse(typeof(DayOfWeek), temp.DeliveryDay) - (int)today.DayOfWeek + 7) % 7) + 7;
DateTime Secondweek = today.AddDays(weekly2);
int weekly3 = (((int)Enum.Parse(typeof(DayOfWeek), temp.DeliveryDay) - (int)today.DayOfWeek + 7) % 7) + 14;
DateTime Thirdweek = today.AddDays(weekly3);
etc..
}
else if (Type == "fortnightly")
{
}
}
例如,使用Type == "fortnightly"
,例如temp.DeliveryDay == "Friday"
,然后基于今天(2月2日),我希望输出为:
February 5th (First Friday after today, since temp.DeliveryDay is friday)
February 19th (14 days or fortnight from the first output)
March 4th
etc.
答案 0 :(得分:1)
首先 - 您重复所有行为以获取每周日期。我建议你分解你的操作。我看到两个主要部分。
此方法可以处理第一部分,
DateTime FirstDayOfWeekAfter(DateTime day, DayOfWeek dayOfWeek)
{
// We don't want to return today.
day = day.AddDays(1);
// If the current tested day is the desired day of week, return.
if (day.DayOfWeek == dayOfWeek)
{
return day;
}
// else call again with the next day.
else
{
return FirstDayOfWeekAfter(day, dayOfWeek);
}
}
这对方法将处理第二部分。我这里有第一种方法,所以当你真正使用它时,没有必要使用(DayOfWeek)。
IEnumerable<DateTime> GetPeriodicDeliveryDates(DateTime today, object dayOfDelivery, int period)
{
return GetPeriodicDeliveryDates(today, (DayOfWeek)dayOfDelivery, period);
}
IEnumerable<DateTime> GetPeriodicDeliveryDates(DateTime today, DayOfWeek dayOfDelivery, int period)
{
// Get the date of the first delivery.
var firstDelivery = FirstDayOfWeekAfter(today, dayOfDelivery);
while (true)
{
// Infinitely yield dates separated by the supplied period length.
yield return firstDelivery;
firstDelivery = firstDelivery.AddDays(period);
}
}
使用这些方法很简单。每周和每两周一次的可枚举之间的唯一区别是传递到GetPeriodicDeliveryDates()
的时期。您确实希望确保不要尝试完全枚举GetPeriodicDeliveryDates()
- 它是无限顺序的。
var today = DateTime.Today;
var temp = new { DeliveryDay = "Friday" };
var weekly = GetPeriodicDeliveryDates(today, Enum.Parse(typeof(DayOfWeek), temp.DeliveryDay), 7);
var fortnightly = GetPeriodicDeliveryDates(today, Enum.Parse(typeof(DayOfWeek), temp.DeliveryDay), 14);
weekly.Take(5).ToList().ForEach(x => Console.WriteLine(x));
Console.WriteLine();
fortnightly.Take(5).ToList().ForEach(x => Console.WriteLine(x));