我正在尝试为我的日历应用程序实施重复模式。 我希望它的工作方式与Outlook设置重复约会时的工作方式相同。
public async Task<ValidationResponse<ReccurrenceModel>> ApplyReccurrencePeriod (string userName, ReccurrenceModel value)
{
var user = await repository.FindByUserName(userName);
var fromDateUTC = DateTime.SpecifyKind(value.FromDate, DateTimeKind.Utc);
var toDateUTC = DateTime.SpecifyKind(value.ToDate, DateTimeKind.Utc);
var dates = new List<DateTime>();
var weeklyReccurrence = value.weeklyReccurrence;
if (value.IsMonday == true)
{
var fromDate = value.FromDate;
var toDate = value.ToDate;
for (var dt = fromDate; dt < toDate; dt = dt.AddDays(1))
{
dates.Add(dt);
}
var savedDates = dates.Where(x => x.DayOfWeek == DayOfWeek.Monday).Select(x => x.Date);
}
// I do the same code to verify every week day
var test = dates.Where(x => x.DayOfWeek == DayOfWeek.Friday).Select(x => x.Date);
}
foreach (var date in savedDates) {
var x = user.Holidays.FirstOrDefault(kvp => kvp.Key == date
&& kvp.Value.StateVal == value.State.StateVal);
var dateUTC = DateTime.SpecifyKind(date, DateTimeKind.Utc);
user.Holidays[dateUTC] = value.State;
}
// save
var updatedUser = await repository.UpdateEmployee(user);
return await Task.FromResult(new ValidationResponse<HolidayModel>()
{
IsValid = true,
Result = updatedUser.Holidays.ContainsKey(dateUTC) ? new HolidayModel() { Date = dateUTC, State = updatedUser.Holidays[dateUTC] } : null
});
}
}
我的代码存在的问题是,只有当我每周复发时,它才有效。我需要使其正常工作才能使第2、3,... n周复发。 如何让它跳过几周?
public class ReccurrenceModel
{
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public int WeeklyReccurrence { get; set; }
public State State { get; set; }
public bool IsMonday { get; set; }
public bool IsTuesday { get; set; }
public bool IsWednesday { get; set; }
public bool IsThursday { get; set; }
public bool IsFriday { get; set; }
public DateTime FromDateToReturn { get; set; }
public DateTime ToDateToReturn { get; set; }
}
答案 0 :(得分:2)
代码有点复杂,有很多行根本没有任何作用。
在这里,我提供了一个代码示例,尽管它一点也不优雅,但可以为您提供所需的行为,下面的代码将创建一个列表,每2、3天重复一次,无论您需要在几周内定义多少天它的电话。
此方法还接受要为其创建重复的DayOfWeek列表
private static void GetRecurrentDays(DateTime fromDate, DateTime untilDate, uint weeklyRecurrence, List<DayOfWeek> recurrenceDays)
{
var recurrenceDates = new List<DateTime>();
for (var dt = fromDate; dt < untilDate; dt = dt.AddDays(1))
{
if (recurrenceDays.Any(day => day.Equals(dt.DayOfWeek)))
{
var lastDate =
recurrenceDates
.LastOrDefault(date => date.DayOfWeek.Equals(dt.DayOfWeek));
// We multiply 7 days (a week) with weeklyRecurrence to
// calculate the appropiate date in which to add another day,
// calling with either 0 or 1 will calculate a weekly
// schedule
if (lastDate.Equals(DateTime.MinValue)
|| weeklyRecurrence.Equals(0)
|| ((dt - lastDate).Days % (7 * weeklyRecurrence)).Equals(0) )
{
recurrenceDates.Add(dt);
}
}
}
}
您可以将此代码嵌入自己的代码中,以获取每周重复的天数,然后在代码中进一步使用它们