繁体   English   中英

检查 c# 中的日期范围是否连续?

[英]Check if date range is sequential in c#?

假设我有一个用户界面,用户可以在其中 select 天。 有没有办法检查所选日期是否是连续的,例如:

4/4、4/5、4/6、4/7、4/8、4/9、4/10 或

4/29、4/30、5/1、5/2、5/3

我知道我可能可以遍历日期范围并检查,但我更好奇是否已经有内置方法来检查这个。

关于上述情况,它们是有序的,它们可以滚动到下个月。

我正在使用 .NET 框架 2.0 并且不能使用 LINQ。

关于汤姆的回答:

DateTime dtStart = new DateTime(2011,5,4);
DateTime dtEnd = new DateTime(2011,5,11);

int numberOfDaysSelected = 7; //Assume 7 days were selected.

TimeSpan ts = dtEnd - dtStart;


if(ts.Days == numberOfDaysSelected - 1)
{
Console.WriteLine("Sequential");
}
else
{
Console.WriteLine("Non-Sequential");
}

我不相信有一种内置方法可以实现您想要的结果,但如果您可以轻松分辨最早和最晚的日期,您可以通过从最晚的日期中减去最早的日期来创建一个新的 TimeSpan,然后验证时间跨度的天数与选择的日期数相匹配 - 1。

你没有告诉我们这些日子是否有安排。

你没有告诉我们它们是否会超过一个月的界限,如

30, 31, 1.

我假设是有序的,并且我假设它们不会超过一个月的边界(因为你的示例是有序的,并且它不会超过一个月的边界)。

然后你可以说

public bool IsSequential(this IEnumerable<DateTime> sequence) {
    Contract.Requires(sequence != null);
    var e = sequence.GetEnumerator();
    if(!e.MoveNext()) {
        // empty sequence is sequential
        return true;
    }
    int previous = e.Current.Date;
    while(e.MoveNext()) {
        if(e.Current.Date != previous.AddDays(1)) {
            return false;
        }      
        previous = e.Current.Date;
    }
    return true;
}

请注意,此解决方案只需要遍历序列一次。 如果您没有有序序列,或者如果您允许超过一个月的边界,则解决方案会更加复杂。

没有内置任何东西,但您可以使用 Linq 轻松构建:

List<DateTime> timeList = new List<DateTime>();
//populate list..
bool isSequential = timeList.Zip(timeList.Skip(1), 
                                 (a, b) => b.Date == a.Date.AddDays(1))
                            .All(x => x);

已编辑-首先将问题误解为按时间递增而不是按顺序递增-修复了该问题。

使用Linq的扩展方法:

public static bool IsContiguous(this IEnumerable<DateTime> dates)
{
    var startDate = dates.FirstOrDefault();

    if (startDate == null)
        return true;

    //.All() doesn't provide an indexed overload :(
    return dates
        .Select((d, i) => new { Date = d, Index = i })
        .All(d => (d.Date - startDate).Days == d.Index);
}

测试它:

List<DateTime> contiguousDates = new List<DateTime>
{
    new DateTime(2011, 05, 05),
    new DateTime(2011, 05, 06),
    new DateTime(2011, 05, 07),
};
List<DateTime> randomDates = new List<DateTime>
{
    new DateTime(2011, 05, 05),
    new DateTime(2011, 05, 07),
    new DateTime(2011, 05, 08),
};

Console.WriteLine(contiguousDates.IsContiguous());
Console.WriteLine(randomDates.IsContiguous());

退货

True
False

编辑

.NET 2-like 答案:

public static bool CheckContiguousDates(DateTime[] dates)
{
    //assuming not null and count > 0
    var startDate = dates[0];

    for (int i = 0; i < dates.Length; i++)
    {
        if ((dates[i] - startDate).Days != i)
            return false;
    }
    return true;
}

您可以使用.NET时间段库的 TimeGapCalculator来查找多个时间段之间的间隙(与顺序、计数和重叠无关):

// ----------------------------------------------------------------------
public void SequentialPeriodsDemo()
{
  // sequential
  ITimePeriodCollection periods = new TimePeriodCollection();
  periods.Add( new Days( new DateTime( 2011, 5, 4 ), 2 ) );
  periods.Add( new Days( new DateTime( 2011, 5, 6 ), 3 ) );
  Console.WriteLine( "Sequential: " + IsSequential( periods ) );

  periods.Add( new Days( new DateTime( 2011, 5, 10 ), 1 ) );
  Console.WriteLine( "Sequential: " + IsSequential( periods ) );
} // SequentialPeriodsDemo

// --------------------------------------------------------------------
public bool IsSequential( ITimePeriodCollection periods, ITimePeriod limits = null )
{
  return new TimeGapCalculator<TimeRange>( 
    new TimeCalendar() ).GetGaps( periods, limits ).Count == 0;
} // IsSequential

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM