Hybrid
Hybrid

Reputation: 596

How to get the 30th of the month after a given date

I have a date value varFinishDate that I pull form an SQL database and I want to get the 30th of the month after varFinishDate. Except if it’s going to be in February when I want it to be the 28th. What is the best way to do this in C#?

To put it in context, we have programs running and the reports are due at the end of the month after they finish (on the 30th even if there are 31 days). So if it finished any time in April the report is due on the 30th of May and so on, except where they finish in January then the reports are due on the 28th of February.

Upvotes: 0

Views: 513

Answers (4)

IHateATMFees
IHateATMFees

Reputation: 346

This should allow for leap years to also use day 29:

var dueDate = varFinishDate.AddMonths(1);
if ( DateTime.DaysInMonth(dueDate.Year, dueDate.Month) < 30 ) {
      dueDate.AddDays(DateTime.DaysInMonth(dueDate.Year, dueDate.Month) - dueDate.Day);
} else {
      dueDate = new DateTime(dueDate.Year,dueDate.Month,30);
}

Upvotes: 0

taylonr
taylonr

Reputation: 10790

Use DaysInMonth();

So you would have something like

var nextMonth = varFinishDate.AddMonths(1);
if(nextMonth.DaysInMonth() < 30)
   nextMonth = new DateTime(nextMonth.Year, nextMonth.Month, 28);
else
    nextMonth = new DateTime(nextMonth.Year, nextMonth.Month, 30);

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134881

How about this?

var nextMonth = varFinishDate.AddMonths(1);
var targetDate = new DateTime(
    nextMonth.Year,
    nextMonth.Month,
    nextMonth.Month == 2 ? 28 : 30);

Upvotes: 3

Anthony Pegram
Anthony Pegram

Reputation: 126884

int day = 30;
if (finishedDate.Month == 1)
    day = 28;

DateTime nextMonth = finishedDate.AddMonths(1);

DateTime reportDate = new DateTime(nextMonth.Year, nextMonth.Month, day); 

Upvotes: 0

Related Questions