我有一个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列表,该列表表示今天的计划。
发布于 2015-07-22 17:55:49
您可以将枚举作为数字进行比较:
if (today >= monday && today <= friday) {正如@Tyrsius所指出的那样,这只是因为monday < friday起作用了。所以,从技术上讲,你需要先检查一下:
if ((monday <= friday && (today >= monday && today <= friday)) ||
(monday > friday && (today <= monday && today >= friday))) {注意到.NETs周周日开始: DayOfWeek.Sunday是0.
如果你想在星期一开始你的一周,你必须做一些算术。
var lowLimit = ((int)monday + 6) % 7;
var highLimit = ((int)friday + 6) % 7;
var valueToCheck = ((int)today + 6) % 7;
if ((lowLimit <= highLimit && (valueToCheck >= lowLimit && valueToCheck <= highLimit)) ||
(lowLimit > highLimit && (valueToCheck <= lowLimit && valueToCheck >= highLimit))) {发布于 2015-07-22 18:20:33
如前所述,您可以在逻辑比较中使用枚举,但存在一个问题,即值不环绕。终点的顺序很重要。例如,“在星期六和星期二之间是星期一”应该返回true,而“在星期二和星期六之间是星期一”应该返回false。
public static bool IsBetween(this DayOfWeek weekday, DayOfWeek inclusiveStart, DayOfWeek inclusiveEnd)
{
if (inclusiveStart <= inclusiveEnd)
{
return (weekday >= inclusiveStart) && (weekday <= inclusiveEnd);
}
return (weekday >= inclusiveStart) || (weekday <= inclusiveEnd);
}这应该能行。做这件事有其他方法,但这是一种方法。
https://stackoverflow.com/questions/31570501
复制相似问题