【发布时间】:2015-07-22 17:52:51
【问题描述】:
我有一个DayOfWeek,我需要检查这一天是否介于另外两个DayOfWeek 变量之间。
例如:
DayOfWeek monday = DayOfWeek.Monday;
DayOfWeek friday= DayOfWeek.Friday;
DayOfWeek today = DateTime.Today.DayOfWeek;
if (today is between monday and friday)
{
...
}
注意:这些日子包括在内。在这种情况下,如果日期是星期一、星期二、星期三、星期四和星期五,那么它是有效的。
我唯一能想到的就是用不同的方法做一个大量的 if 语句,也许是一个扩展方法,但这不是很优雅。
编辑
这是我的要求示例:
public enum RecurringModes
{
Minutes,
Hours
}
public RecurringModes RecurringMode { get; set; }
public int RecurringValue { get; set; }
...
public IEnumerable<DateTime> AllDueDatesToday()
{
//Get the current date (starting at 00:00)
DateTime current = DateTime.Today;
//Get today and tomorrow's day of week.
DayOfWeek today = current.DayOfWeek;
DayOfWeek tomorrow = current.AddDays(1).DayOfWeek;
//If it isn't in the date range, then return nothing for today.
if (!IsInDateRange(today, StartingOn, EndingOn))
yield break;
while (current.DayOfWeek != tomorrow)
{
//Check the selected recurring mode
switch (RecurringMode)
{
//If it's minutes, then add the desired minutes
case RecurringModes.Minutes:
current = current.AddMinutes(RecurringValue);
break;
//If it's hours, then add the desired hours.
case RecurringModes.Hours:
current = current.AddHours(RecurringValue);
break;
}
//Add the calculated date to the collection.
yield return current;
}
}
public bool IsInDateRange(DayOfWeek day, DayOfWeek start, DayOfWeek end)
{
//if they are all the same date
if (start == end && start == day)
return true;
//This if statement is where the problem lies.
if ((start <= end && (day >= start && day <= end)) ||
(start > end && (day <= start && day >= end)))
return true;
else return false;
}
实际上,AllDueDatesToday() 方法将返回一个 DateTime 列表,它代表今天的日程安排。
【问题讨论】:
标签: c# extension-methods dayofweek