Check if datetime instance falls in between other two datetime objects

℡╲_俬逩灬. 提交于 2019-11-27 04:20:33

DateTime.Ticks will account for the time. Use .Ticks on the DateTime to convert your dates into longs. Then just use a simple if stmt to see if your target date falls between.

// Assuming you know d2 > d1
if (targetDt.Ticks > d1.Ticks && targetDt.Ticks < d2.Ticks)
{
    // targetDt is in between d1 and d2
}  

Do simple compare > and <.

if (dateA>dateB && dateA<dateC)
    //do something

If you care only on time:

if (dateA.TimeOfDay>dateB.TimeOfDay && dateA.TimeOfDay<dateC.TimeOfDay)
    //do something

You can use:

if ((DateTime.Compare(dateToCompare, dateIn) == 1) && (DateTime.Compare(dateToCompare, dateOut) == 1)
{
   //do code here
}

or

if ((dateToCompare.CompareTo(dateIn) == 1) && (dateToCompare.CompareTo(dateOut) == 1))
{
   //do code here
}
Wayne Hamberg

Write yourself a Helper function:

public static bool IsBewteenTwoDates(this DateTime dt, DateTime start, DateTime end)
{
    return dt >= start && dt <= end;
}

Then call: .IsBewteenTwoDates(DateTime.Today ,new DateTime(,,));

This will help for sure.

public static int year1, year2, year3, month1, month2, month3, day1, day2, day3;
    public static string dateA, dateB, dateC;
    static bool iswithindaterange(string dateA, string dateB, string dateC)
    {
        month1 = Convert.ToInt32((dateA.Split('/'))[0]); // Splits the value of the string on the '/' into month , day and year
        day1 = Convert.ToInt32((dateA.Split('/'))[1]);
        year1 = Convert.ToInt32((dateA.Split('/'))[2]);

        month2 = Convert.ToInt32((dateB.Split('/'))[0]);
        day2 = Convert.ToInt32((dateB.Split('/'))[1]);
        year2 = Convert.ToInt32((dateB.Split('/'))[2]);

        month3 = Convert.ToInt32((dateC.Split('/'))[0]);
        day3 = Convert.ToInt32((dateC.Split('/'))[1]);
        year3 = Convert.ToInt32((dateC.Split('/'))[2]);

        DateTime startdate = new DateTime(year1, month1, day1);
        DateTime enddate = new DateTime(year2, month2, day2); 
        DateTime checkdate = new DateTime(year3, month3, day3);

        if (checkdate >= startdate && checkdate <= enddate)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    static void Main(string[] args)
    {
        dateA = "1/22/2016"; // Date Format (MM/dd/YYYY)
        dateB = "9/20/2016";
    dateC = "5/18/2016";
        bool answer;
        answer = iswithindaterange(dateA, dateB, dateC);
        if (answer == true)
        {
            Console.WriteLine("True");
        }
        else
        {
            Console.WriteLine("False");
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!