我目前想从日期列表中获取日期范围(时间范围内)。从日期列表中获取时间范围
例如:
现在的时间是
2017年4月8日18:00
而且我得到了这些从和日期:
public static string[] fromDates = new string[] { "2017-04-07 07:00", "2017-04-07 10:00", "2017-04-07 12:00", "2017-04-07 14:00", "2017-04-07 16:00" };
public static string[] toDates = new string[] { "2017-04-07 08:00", "2017-04-07 11:00", "2017-04-07 13:00", "2017-04-07 15:00", "2017-04-07 17:00" };
我使用此代码:
public static bool IsInRange(this DateTime dateToCheck, string[] startDates, string[] endDates, out string StartDate, out string EndDate)
{
DateTime startDate = new DateTime();
DateTime endDate = new DateTime();
bool isWithinRange = false;
for (int i = 0; i < startDates.Length; i++)
{
startDate = Convert.ToDateTime(startDates[i]);
isWithinRange = dateToCheck >= startDate;
if (isWithinRange)
break;
}
for (int y = 0; y < endDates.Length; y++)
{
endDate = Convert.ToDateTime(endDates[y]);
isWithinRange = dateToCheck < endDate;
if (isWithinRange)
break;
}
StartDate = startDate;
EndDate = endDate;
return isWithinRange;
}
我这样称呼它:
var isBetween = Convert.ToDateTime("2017-04-08 18:00").IsInRange(fromDates, toDates, out StartDate, out EndDate)
但我不能让它工作,在StartDate
在IsInRange
方法总是返回true,将它从fromDates
变量,它是返回的第一个索引错误。
我怎样才能让它像之间的时间?
我知道我能做到这一点是这样的:
var isBetween = dateToCheck >= startDate && dateToCheck < endDate
但它只有一个日期需要检查,那如果是喜欢我的情况?
您的回答非常感谢。
感谢
我正准备发布这些确切的更改:) –
感谢您的回答和建议@Pawel Gradecki,我想接受你的答案,但他们(stackoverflow)不是允许我这样做:)。将尝试乔恩Skeet的建议和你的重新设计我的代码。 – Trinity
请注意,代码目前不会编译 - 循环后的'return'语句需要*。我建议你根本不需要'isWithinRange',但如果你到达循环结尾,你可以返回'true'而不是'break'语句,并且返回false。 –