c# - 从日期列表中获取时间范围

标签 c# asp.net

我目前想从日期列表中获取日期范围(时间范围之间)。

例如:

现在是

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

但是只有一个日期需要检查,如果是像我这样的情况呢?

非常感谢您的回答。

谢谢

最佳答案

我将从将所有内容转换为更有用的对象模型开始:

  • 摆脱所有的字符串(即尽早从字符串转换为更有用的东西)
  • 创建一个指示“日期/时间范围”的新类型,而不是两个集合。将错误的项目关联在一起会有些挫败:起始值彼此不相关,它们与其相应的结束日期相关。

如果确实需要,您可以在方法中执行此操作,但最好为尽可能多的代码迁移到更丰富的对象模型。例如,假设您有:

public sealed class DateTimeRange
{
    public DateTime Start { get; }
    public DateTime End { get; }

    public DateTimeRange(DateTime start, DateTime end)
    {
        // TODO: Validate that start <= end
        Start = start;
        End = end;
    }

    public bool Contains(DateTime value) => Start <= value && value < End;
}

那么你的方法可以是这样的:

public DateTimeRange FindRange(IEnumerable<DateTimeRange> ranges, DateTime value) =>
    ranges.FirstOrDefault(range => range.Contains(value));

如果没有范围包含该值,则返回 null,否则第一个 包含值。

(顺便说一句,我会在 Noda Time 中执行所有这些操作,而不是作为更好的日期/时间 API,但我有偏见。)

关于c# - 从日期列表中获取时间范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43291403/

相关文章:

c# - C# 中的语法启用模式是什么?

c# - 迭代器中使用的模式

c# - ASP.NET vNext - KVM 无法加载文件

c# - SQL Server 使用 datetime2 查询今天的日期

c# - 使用 KeyDown 事件平滑地移动控件

c# - 使用智能手机上的 RIL Audio 进行音频反馈

c# - 在 C# 代码隐藏中创建和发布表单的最佳方式

c# - 在不知道主键的情况下插入多个表

c# - 确定缩短 URL 的最终目的地

c# - Excel 日期值