简体   繁体   English

净DateTime.AddMonths(1)与Javascript d.setMonth(d.getMonth()+ 1)不同

[英]Net DateTime.AddMonths(1) doesn't work the same as Javascript d.setMonth(d.getMonth() + 1)

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. 我具有客户端日期验证功能,该功能要求一个特定的日期必须与另一个日期d.setMonth(d.getMonth() + 1)一个月,因此我使用d.setMonth(d.getMonth() + 1)并且大多数情况下都可以正常工作。

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. 对于1/31/2009中的月末问题,它将返回3/3/2009,这很棒-这就是我希望它处理它的方式。

In the code behind, I'm also generating this date but DateTime.AddMonths(1) returns 2/28/2009 so that's no good. 在后面的代码中,我也生成了此日期,但DateTime.AddMonths(1)返回2/28/2009,所以这样做不好。

Is there some way around this? 有办法解决吗?

The .NET function is undoubtedly more intelligent. .NET功能无疑更加智能。 But if you want to dumb it down to behave like Javascript, add 31 days instead... 但是,如果您想使其表现像Javascript,则可以增加31天...

DateTime.AddDays(31)

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. 从您将1/31/2009的示例更改为3/3/2009,这听起来像是您只想要一种将指定日期提前其相应月份的天数的方法。 (Adding 31 days to the date if it's in January, 28 if in February during a non-leap year, etc...) (如果是非January年,则在日期中添加31天,如果是1月,则添加28天;如果是非le年的2月,则添加28天,等等。)

So your code would look something like: 因此,您的代码将类似于:

d = d.AddDays(DateTime.DaysInMonth(d.Year, d.Month))

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. 添加到Josh的答案中……不确定为什么要这样做,但是如果您确实想要某种未内置的特定行为,请记住您具有编写扩展名的能力。 This extension adds a method called "AddMonthsJ" to DateTime. 此扩展将一个名为“ AddMonthsJ”的方法添加到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));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM