tags:

views:

124

answers:

7

Hello,

lets say, I have 28th of February 2010 and add one months to this date using AddMonths(1)...the resulting date is 28th of March, but not 31st of March, which I want. Is there a way to tweak that a bit so this works without adding custom code?

Edit: I dont need the last day of a month, actually I need to add one month, but when its the last day of a month, I need to find the last day of the next month.

Thanks!

A: 

No - it doesn't take that into account. It's custom code all the way!

Will your code only be interested in the last day of months, or do you want code to add a month to any date, but take into account when the date supplied is the last day of the month?

David
Elaborating on Graphain's comment, when you are satisfied with an answer, it is expected that you mark the answer by clicking on the tick symbol. This ups your 'accept rate'.Some people get very hissy about other people with low accept rates and won't answer their questions.
David
Yeah, the last day of the months would suffice as well I think...Ill mark the answer as soon as it works :)
grady
See my edit of the original post
grady
A: 

Try overloading the day property and setting it to 32. Whgen this is done in JavaScript, I believe it defaults back to the last day of whatever month you're in.

Sam Nicholson
If you mean *set* the day property - it is immutable (this is C# - see the tags on the question).
Marc Gravell
Woah! Sorry. I didn't realise you couldn't do that in C#.
Sam Nicholson
+5  A: 

I don't know what you want to achieve, but you could add one day, add a month and subtract one day.

DateTime nextMonth = date.AddDays(1).AddMonths(1).AddDays(-1);

EDIT:

As one of the commenters points out, this sometimes gives the wrong result. After reading your updated question, I think the easiest way of calculating the date you want is:

public static DateTime NextMonth(this DateTime date)
{
   if (date.Day != DateTime.DaysInMonth(date.Year, date.Month))
      return date.AddMonths(1);
   else 
      return date.AddDays(1).AddMonths(1).AddDays(-1);
}

This extension method returns next month's date. When the current date is the last day of the month, it will return the last day of next month.

Philippe Leybaert
Clever - that would work if he's guaranteed to have the last day of the month already.
Graphain
If he doesn't, the result is the same as AddMonths(1)
Philippe Leybaert
@Philippe - For the 30th of January, it isn't.
Damien_The_Unbeliever
@Damien: you're right :)
Philippe Leybaert
+2  A: 

If you mean that the resultant date should be the same distance from the end of the month, then you're into custom code - something like (not fully tested, especially re 28/30/31 months):

class Program
{
    static void Main()
    {
        var when = DateTime.Today;
        DateTime fromEndOfNextMonth = when.AddMonthsRelativeToEndOfMonth(1);
    }

}
public static class DateTimeExtensions
{
    public static DateTime AddMonthsRelativeToEndOfMonth(
               this DateTime when, int months)
    {
        if (months == 0) return when;
        DateTime startOfNextMonth = when;
        int month = when.Month;
        while (startOfNextMonth.Month == month)
        {
            startOfNextMonth = startOfNextMonth.AddDays(1);
        }
        TimeSpan delta = startOfNextMonth - when;
        return startOfNextMonth.AddMonths(1) - delta;
    }

}
Marc Gravell
I hope "when" is not going to be a reserved keyword in C# 5.0 :-)
Philippe Leybaert
A: 

I solved it now, by checking if it is the last day of a month using GetLastDayInCurrentMonth. If thats the case, I use

DateTime nextMonth = date.AddDays(1).AddMonths(1).AddDays(-1);

If its not the last day, I just use AddMonths(1)

Thanks guys!

grady
A: 
if(yourDate.Day == DaysInMonth(yourDate.Year,yourDate.Month)) //check for last day
    yourDate.AddDays(DateTime.DaysInMonth(yourDate.Year,(yourDate.Month+1)%12));
Veer
What if your date is in december?
Philippe Leybaert
@Philippe Leybaert: Thanks for spotting that out. check my edit.
Veer
A: 
public static class DateTimeExtensions
{
    public static DateTime AddMonthsCustom(this DateTime source, int months)
    {
        DateTime result = source.AddMonths(months);
        if (source.Day != DateTime.DaysInMonth(source.Year, source.Month))
            return result;

        return new DateTime(result.Year, result.Month,
                            DateTime.DaysInMonth(result.Year, result.Month),
                            result.Hour, result.Minute, result.Second,
                            result.Millisecond, result.Kind);
    }
}
LukeH