How to know if a DateTime is between a DateRange i

2019-01-03 06:01发布

I need to know if a Date is between a DateRange. I have three dates:

// The date range
DateTime startDate;
DateTime endDate;

DateTime dateToCheck;

The easy solution is doing a comparison, but is there a smarter way to do this?

Thanks in advance.

5条回答
Explosion°爆炸
2楼-- · 2019-01-03 06:31

You can use:

return (dateTocheck >= startDate && dateToCheck <= endDate);
查看更多
爷、活的狠高调
3楼-- · 2019-01-03 06:36

Usually I create Fowler's Range implementation for such things.

public interface IRange<T>
{
    T Start { get; }
    T End { get; }
    bool Includes(T value);
    bool Includes(IRange<T> range);
}

public class DateRange : IRange<DateTime>         
{
    public DateRange(DateTime start, DateTime end)
    {
        Start = start;
        End = end;
    }

    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public bool Includes(DateTime value)
    {
        return (Start <= value) && (value <= End);
    }

    public bool Includes(IRange<DateTime> range)
    {
        return (Start <= range.Start) && (range.End <= End);
    }
}

Usage is pretty simple:

DateRange range = new DateRange(startDate, endDate);
range.Includes(date)
查看更多
做个烂人
4楼-- · 2019-01-03 06:39

Nope, doing a simple comparison looks good to me:

return dateToCheck >= startDate && dateToCheck < endDate;

Things to think about though:

  • DateTime is a somewhat odd type in terms of time zones. It could be UTC, it could be "local", it could be ambiguous. Make sure you're comparing apples with apples, as it were.
  • Consider whether your start and end points should be inclusive or exclusive. I've made the code above treat it as an inclusive lower bound and an exclusive upper bound.
查看更多
地球回转人心会变
5楼-- · 2019-01-03 06:55

I’ve found the following library to be the most helpful when doing any kind of date math. I’m still amazed nothing like this is part of the .Net framework.

http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

查看更多
老娘就宠你
6楼-- · 2019-01-03 06:56

You could use extension methods to make it a little more readable:

public static class DateTimeExtensions
{
    public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate)
    {
        return dateToCheck >= startDate && dateToCheck < endDate;
    }
}

Now you can write:

dateToCheck.InRange(startDate, endDate)
查看更多
登录 后发表回答