Get the specific dates of moths considering a specific logic

I am doing a code where I am stuck in a case :-

I am having a date : 31 jan 2014, and i want to get dates after every 1 month in a way that next date should be 28 feb,2014 but because feb does not have 31 so I should get 28. Than march is having 31 so it should have 31 . basically a list which have

31 jan 2014
28 feb 2014
31 march 2014
30 april 2014
31 may 2014

Now if that date is : 29 jan 2014 than a list

29 jan 2014
28 feb 2014
29 march 2014
29 april 2014
29 may 2014

and i want to consider leap years to that too.

I was trying to use addmonths(1) function but in a loop when i try to add it

31 jan 2014, 28 feb 2014, 28 march 2014,28 april 2014,28 may 2014.

which was wrong.

Can anyone tell me the correct way to get the thing done.

Answers


The approach works:

DateTime start = new DateTime(2014, 1, 31);
for(int i=0; i<12; i++)
  Console.WriteLine(start.AddMonths(i));

To get last date of the month you can use,

var thisMonthStart = DateTime.Today.AddDays(1 - DateTime.Today.Day);
var thisMonthEnd = thisMonthStart.AddMonths(1).AddSeconds(-1);

So just give a try with.

AddMonths(1).AddSeconds(-1)

You can get last date of the next month.


Use Calendar class for adding months.

Calendar cal = CultureInfo.InvariantCulture.Calendar;
DateTime initialDT = new DateTime(2014,1,31,cal);
DateTime dt = cal.AddMonths(initialDT,1);

The below should work

static void Test5()
{
    DateTime start = new DateTime(2014, 1, 29);
    DateTime nextDate = start;

    for (int i = 0; i < 5; i++)
    {
        nextDate = nextDate.AddMonths(1);

        if (start.Day == DateTime.DaysInMonth(start.Year, start.Month))
        {
            // If the start date was the end of the month, then set the generated date to end of the month as well
            // e.g. 31/1 -> 28/2 -> 31/3 -> 30/4 -> 31/5 ... and so on
            int endDay = DateTime.DaysInMonth(nextDate.Year, nextDate.Month);
            nextDate = new DateTime(nextDate.Year, nextDate.Month, endDay);
        }
        else
        {
            // Try to set the day to same as start day
            if (start.Day <= DateTime.DaysInMonth(nextDate.Year, nextDate.Month))
            {
                nextDate = new DateTime(nextDate.Year, nextDate.Month, start.Day);
            }
        }

        Console.WriteLine(nextDate.ToString("dd/MM/yyyy"));
    }
}

Need Your Help

What happens when BEFORE INSERT TRIGGER fails in oracle

oracle exception plsql triggers

I have a small doubt regarding BEFORE INSERT TRIGGER in oracle,