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开发者_StackOverflow January then the reports are due on the 28th of February.
How about this?
var nextMonth = varFinishDate.AddMonths(1);
var targetDate = new DateTime(
nextMonth.Year,
nextMonth.Month,
nextMonth.Month == 2 ? 28 : 30);
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);
int day = 30;
if (finishedDate.Month == 1)
day = 28;
DateTime nextMonth = finishedDate.AddMonths(1);
DateTime reportDate = new DateTime(nextMonth.Year, nextMonth.Month, day);
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);
}
精彩评论