Hi, I've got a date range between a start and end date, which has to be each month on the valuation day,

but if end date(2010/07/20) is before the valuation date(2010/07/31), the valuation month for that month must be displayed.

if (endDate.Day < validDay) is true, then it works perfect. but if it's false, it duplicates all of the fields.

I tried this in my code:

public List<DateTime> GetDates(DateTime startDate, DateTime endDate, int validDay)
    {
        TimeSpan span;
        span = endDate - startDate;

        List<DateTime> result = new List<DateTime>();

        DateTime dateToParse = DateTime.MinValue + span;

        int yearMonths = 0;
        if (dateToParse.Year > 0)
        {
            yearMonths = (dateToParse.Year - 1) * 12;
        }

        int monthCount = (yearMonths + dateToParse.Month) - 1;

                  // ************* Here is the problem
        int lastRow = 0;
        if (endDate.Day < validDay)
            lastRow = (monthCount + 1);
        else
            lastRow = monthCount;

        for (int i = 0; i < lastRow; i++)
        {
            DateTime currDate = endDate.AddMonths(-(monthCount - i));
            int lastDayOfMonth = DateTime.DaysInMonth(currDate.Year, currDate.Month);
            currDate = new DateTime(currDate.Year, currDate.Month, lastDayOfMonth);
            if (endDate.Day > validDay)
            {
                currDate = new DateTime(currDate.Year, currDate.Month, validDay);
                    result.Add(currDate);
            }
            if (currDate.Day <= validDay)
            {
                result.Add(currDate);
            }
            else
            {
                currDate = new DateTime(currDate.Year, currDate.Month, validDay);
                result.Add(currDate);
            }
        }

        return result;
    }

>date range

Sorry, I'm not quite following the problem. My understanding from your code is that you want to get dates between give dates.

Maybe you are missing else.

if (endDate.Day > validDay)
                {
                    currDate = new DateTime(currDate.Year, currDate.Month, validDay);
                    result.Add(currDate);
                }
                else
                if (currDate.Day <= validDay)
                {
                    result.Add(currDate);
                }
                else
                {
                    currDate = new DateTime(currDate.Year, currDate.Month, validDay);
                    result.Add(currDate);
                }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.