Development Tip

C #에서 DateTime이 DateRange 사이에 있는지 확인하는 방법

yourdevel 2020. 11. 12. 20:26
반응형

C #에서 DateTime이 DateRange 사이에 있는지 확인하는 방법


Date가 DateRange 사이에 있는지 알아야합니다. 세 가지 날짜가 있습니다.

// The date range
DateTime startDate;
DateTime endDate;

DateTime dateToCheck;

쉬운 해결책은 비교하는 것이지만이를 수행하는 더 현명한 방법이 있습니까?

미리 감사드립니다.


아니요, 간단한 비교를하는 것이 나에게 좋습니다.

return dateToCheck >= startDate && dateToCheck < endDate;

그래도 고려해야 할 사항 :

  • DateTime시간대 측면에서 다소 이상한 유형입니다. UTC 일 수도 있고 "로컬"일 수도 있고 모호 할 수도 있습니다. 사과와 사과를 비교하고 있는지 확인하십시오.
  • 출발지와 도착지가 포괄적인지 배타적인지 고려하십시오. 위의 코드를 포괄적 인 하한과 배타적 인 상한으로 취급하도록 만들었습니다.

보통 나는 그런 것들을 위해 Fowler의 Range 구현을 만듭니다 .

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);
    }
}

사용법은 매우 간단합니다.

DateRange range = new DateRange(startDate, endDate);
range.Includes(date)

확장 메서드를 사용하여 좀 더 읽기 쉽게 만들 수 있습니다.

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

이제 다음과 같이 작성할 수 있습니다.

dateToCheck.InRange(startDate, endDate)

You can use:

return (dateTocheck >= startDate && dateToCheck <= endDate);

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


Following on from Sergey's answer, I think this more generic version is more in line with Fowler's Range idea, and resolves some of the issues with that answer such as being able to have the Includes methods within a generic class by constraining T as IComparable<T>. It's also immutable like what you would expect with types that extend the functionality of other value types like DateTime.

public struct Range<T> where T : IComparable<T>
{
    public Range(T start, T end)
    {
        Start = start;
        End = end;
    }

    public T Start { get; }

    public T End { get; }

    public bool Includes(T value) => Start.CompareTo(value) <= 0 && End.CompareTo(value) >= 0;

    public bool Includes(Range<T> range) => Start.CompareTo(range.Start) <= 0 && End.CompareTo(range.End) >= 0;
}

참고URL : https://stackoverflow.com/questions/4781611/how-to-know-if-a-datetime-is-between-a-daterange-in-c-sharp

반응형