Question

I am working on an application in asp.net with XML as data source where I am asking users to input 2 dates from 2 textboxes in the form "dd/MM" and not including the year. and I need to find all the details of the employee whose birthday lies in that range of date. The XML has details of all the employee and the DOB is saved in the form of "dd/MM". I tried different logics bt dint work out. so please suggest me how to tackle this problem. thanks in advance.

Was it helpful?

Solution

A simple approach is the one I specified in the comments. Using Linq it can be used similar to the following.

namespace Test {
public class BirthdayTest
{
    public HasBirthday[] birthdays = new[] {
        new HasBirthday { Name = "Name1", Birthday = new DateTime(2014, 1, 1) },
        new HasBirthday { Name = "Name2", Birthday = new DateTime(2014, 2, 14) }
    };

    public class HasBirthday {
        public DateTime Birthday { get; set; }
        public string Name { get; set; }
    }

    public IEnumerable<HasBirthday> InRange(string from, string to) {
        int firstMonth = Int32.Parse(from.Substring(3));
        int lastMonth = Int32.Parse(to.Substring(3));
        int firstDay = Int32.Parse(from.Substring(0, 2));
        int lastDay = Int32.Parse(to.Substring(0, 2));

        IEnumerable<HasBirthday> inRange = birthdays
            .Where(birthday =>
           birthday.Birthday.Month <= lastMonth &&
           birthday.Birthday.Month >= firstMonth &&
           (birthday.Birthday.Month != lastMonth || birthday.Birthday.Day <= lastDay) &&
           (birthday.Birthday.Month != firstMonth || birthday.Birthday.Day >= firstDay));

        return inRange;
    }
}
}

And then call it with your two dates in the form of "dd/MM". Notice the last "split" when breaking years.

string from = "01/01";
string to = "31/12";
Console.WriteLine("between {0} and {1}", from, to);
foreach (HasBirthday birthday in InRange(from, to)){
    Console.WriteLine("{0}, {1}", birthday.Name, birthday.Birthday);
}

from = "01/02";
to = "31/12";
Console.WriteLine("between {0} and {1}", from, to);
foreach (HasBirthday birthday in InRange(from, to)){
    Console.WriteLine("{0}, {1}", birthday.Name, birthday.Birthday);
}

from = "01/12";
to = "02/01";
Console.WriteLine("between {0} and {1}", from, to);
foreach (HasBirthday birthday in InRange(from, "31/12")){
    Console.WriteLine("{0}, {1}", birthday.Name, birthday.Birthday);
}
foreach (HasBirthday birthday in InRange("01/01", to)){
    Console.WriteLine("{0}, {1}", birthday.Name, birthday.Birthday);
}

Which outputs:

between 01/01 and 31/12
Name1, 1/1/2014 12:00:00 AM
Name2, 2/14/2014 12:00:00 AM
between 01/02 and 31/12
Name2, 2/14/2014 12:00:00 AM
between 01/12 and 02/01
Name1, 1/1/2014 12:00:00 AM
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top