【发布时间】:2017-04-08 07:28:47
【问题描述】:
我目前想从日期列表中获取日期范围(时间范围之间)。
例如:
现在是时候了
2017-04-08 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)
但我不能让它工作,IsInRange 方法中的StartDate 总是返回 true,它会从 fromDates 变量返回第一个索引,这是错误的。
我怎样才能让它像中间的时间?
我知道我可以这样做:
var isBetween = dateToCheck >= startDate && dateToCheck < endDate
但是只需要检查一个日期,如果和我的情况一样呢?
非常感谢您的回答。
谢谢
【问题讨论】: