Standards for Date/Time addition?

前端 未结 8 1241
自闭症患者
自闭症患者 2021-02-02 15:40

I\'m looking for standards for Date/Time addition. I haven\'t been able to find any. In particular I\'m hoping to find a spec that defines what should happen when you add a mont

8条回答
  •  甜味超标
    2021-02-02 16:14

    In the .NET framework the behavior of System.DateTime.AddMonths is as follows:

    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 [rather than April 31st].

    I've tested how it works exactly:

    Console.WriteLine(new DateTime(2008,2,27).AddMonths(1));
    Console.WriteLine(new DateTime(2008,2,28).AddMonths(1));
    Console.WriteLine(new DateTime(2008,2,29).AddMonths(1));
    Console.WriteLine(new DateTime(2011,2,27).AddMonths(1));
    Console.WriteLine(new DateTime(2011,2,28).AddMonths(1));
    Console.WriteLine(new DateTime(2008,1,30).AddMonths(1));
    Console.WriteLine(new DateTime(2008,1,31).AddMonths(1));
    Console.WriteLine(new DateTime(2011,1,30).AddMonths(1));
    Console.WriteLine(new DateTime(2011,1,31).AddMonths(1));
    /* output
    3/27/2008 12:00:00 AM
    3/28/2008 12:00:00 AM
    3/29/2008 12:00:00 AM
    3/27/2011 12:00:00 AM
    3/28/2011 12:00:00 AM
    2/29/2008 12:00:00 AM
    2/29/2008 12:00:00 AM
    2/28/2011 12:00:00 AM
    2/28/2011 12:00:00 AM
        */
    

提交回复
热议问题