views:

155

answers:

3

I have client side date validation that requires one particular Date to be one month from a different date so I use d.setMonth(d.getMonth() + 1) and mostly works just fine.

For end of month issues as in 1/31/2009, it returns 3/3/2009 and that's great - that's how I'd prefer it handle it.

In the code behind, I'm also generating this date but DateTime.AddMonths(1) returns 2/28/2009 so that's no good.

Is there some way around this?

+3  A: 

The .NET function is undoubtedly more intelligent. But if you want to dumb it down to behave like Javascript, add 31 days instead...

DateTime.AddDays(31)
Josh Stodola
You'd think so, but for 2/1/2009 I want to get 3/1/2009 so that doesn't work.
HighHat
Oh wow. So one month after 1/31 is 3/3. And one month after 2/1 is 3/1. That makes a whole lot of sense, now doesn't it?
Josh Stodola
Oh i know it doesn't actually make sense but I have to make the website mimic the behavior of the desktop app that I have no control or say over. Don't take it personal.
HighHat
A: 

From your example of 1/31/2009 being changed to 3/3/2009 it sounds like you just want a way to advance the specified date by the number of days in its respective month. (Adding 31 days to the date if it's in January, 28 if in February during a non-leap year, etc...)

So your code would look something like:

d = d.AddDays(DateTime.DaysInMonth(d.Year, d.Month))
Stephen Mesa
A: 

Adding to Josh's answer... Not really sure why you want to do this but if you do want a specific behavior that is not built in, remember that you have the ability to write extensions. This extension adds a method called "AddMonthsJ" to DateTime. This gives the behavior that I think you are looking for and allows for it to be easily used. You could modify the extension to be whatever you are looking for in changing months.

class Program
{
    static void Main(string[] args)
    {
        DateTime myDate = DateTime.Parse("01/31/2009");

        myDate = myDate.AddMonthsJ(1);

        Console.WriteLine(myDate.ToShortDateString());

        Console.ReadLine();
    }
}

public static class Extensions
{
    public static DateTime AddMonthsJ(this DateTime oldDate, int months)
    {
        return (oldDate.AddDays(months * 31));
    }
}
Bomlin