Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a DateTime range is within another 3 month DateTime range

Tags:

c#

asp.net-3.5

Hi I have a Start Date and End Date per record in a db.

I need to check to see where the time period falls in a 2 year period broken into two lots of quarters then display what quarters each record falls into.

Quarter 1 includes June 09, Jul 09, Aug 09
Quarter 2 includes Sept 09, Oct 09, Nov 09
Quarter 3 includes Dec 09, Jan 10, Feb 10
Quarter 4 includes Mar 10, Apr 10, May 10
Quaretr 5 includes Jun 10, Jul 10...

e.g. 01/10/09 - 01/06/10 would fall into quarters 2, 3, 4 & 5

I am very new to .NET so any examples would be much appreciated.

like image 417
Jamie Avatar asked Apr 22 '10 06:04

Jamie


People also ask

How do you check if a DateTime is in a range?

Datetime objects are comparable, so you can compare datetime objects using the < , > , <= , >= , and == comparison operators. Therefore, you can use the expression start <= current <= end to check if a current time falls into the interval [start, end] when assuming that start , end , and current are datetime objects.

How do you check if a date falls within a range in Java?

The idea is quite simple, just use Calendar class to roll the month back and forward to create a “date range”, and use the Date. before() and Date. after() to check if the Date is within the range.


1 Answers

This should work for you also.

class Range
{
    public DateTime Begin { get; private set; }
    public DateTime End { get; private set; }
    public Range(DateTime begin, DateTime end)
    {
        Begin = begin;
        End = end;
    }

    public bool Contains(Range range)
    {
        return range.Begin >= Begin && range.End <= End;
    }
}

and then to use it

        List<Range> ranges = new List<Range>();

        ranges.Add(new Range(DateTime.Now, DateTime.Now.AddMonths(3)));
        ranges.Add(new Range(DateTime.Now.AddMonths(3), DateTime.Now.AddMonths(6)));

        Range test = new Range(DateTime.Now.AddMonths(1), DateTime.Now.AddMonths(2));

        var hits = ranges.Where(range => range.Contains(test));

        MessageBox.Show(hits.Count().ToString());
like image 91
Greg Bogumil Avatar answered Nov 06 '22 06:11

Greg Bogumil