## 3 replies

Last post Nov 24, 2015 09:07 AM by gerryLowry

• Melody_xxxx

Member

77 Points

74 Posts

```DateTime start = new DateTime(2015, 11, 30);

The result is : 2015-12-30

But I want : 2015-12-31

• PatriceSc

All-Star

40120 Points

12972 Posts

Hi,

You have several ways to do that. Assuming this is more general and you want always the last day of a given month, my personal preference is to use the 1st of the month for my calculation. Then using AddMonths(1).AddDays(-1); on the result easily gives me the last day for this month.

You could also use https://msdn.microsoft.com/en-us/library/system.datetime.daysinmonth(v=vs.110).aspx and do the adjustement etc...

• Nan Yu

All-Star

15725 Points

2618 Posts

Microsoft

Nov 24, 2015 08:45 AM|Nan Yu|LINK

Hi Melody ,

And try to use below code :

```public static DateTime GetFirstDayOfNextMonth(DateTime startDate)
{
if (startDate.Month == 12) // its end of year , we need to add another year to new date:
{
startDate = new DateTime((startDate.Year + 1), 1, 1);
}
else
{
startDate = new DateTime(startDate.Year, (startDate.Month + 1), 1);
}
return startDate;
}

public static DateTime GetLastDayOfNextMonth(DateTime startDate)
{
return GetFirstDayOfNextMonth(startDate).AddMonths(1).Subtract(new TimeSpan(1, 0, 0, 0, 0));
}

```
```            DateTime today = new DateTime(2015, 11, 30);
Response.Write(GetLastDayOfNextMonth(today).ToString("yyyy-MM-dd"));```

Best Regards,

Nan Yu

MSDN Community Support
• gerrylowry

Star

14297 Points

5880 Posts

From the MSDN Remarks:

The AddMonths method calculates the resulting month and year,
taking into account leap years and the number of days in a month,
then adjusts the day part of the resulting DateTime object.

If the resulting day is not a valid day in the resulting month,
the last valid day of the resulting month is used.

For example, March 31st + 1 month = April 30th.
The time-of-day part of the resulting DateTime object
remains the same as this instance.

MSDN is in error ... it should read:

then adjusts the day part of the resulting DateTime object.
only if the resulting day is not a valid day in the resulting month

Melody_xxxx, i think you need a kludge.    TIMTOWTDI

Example:  if you are always adding one month to your end of month date, this should work AFAIK:

```DateTime start     = new DateTime(2015, 04, 30);
switch (start.Month)
{
case 2:
break;
case 4:
case 6:
case 9:
case 10: daysToAdd = 1; break;
default: break;
}
Console.WriteLine(endOfMonth);```

output:

`2015-05-31 00:00:00`

if you are adding multiple months, you would need to look a the month before your last month.

edit:

simpler is:

```DateTime start = new DateTime(2015, 04, 30);