DateTime.AddMonths adding only month not days

datetime add month python
add months to current date in c#
how to add 1 month to current date in asp net
datetime::add month php
c# addmonths negative
datetime add month javascript
how to add 30 days to current date in c#
c# last day of month

Let's say, I have 28th of February 2010 and add one month to this date using AddMonths(1)... the resulting date is March 28th, 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 don't 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.

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.

DateTime.AddMonths(Int32) Method (System), AddMonths() method return a new DateTime object that add the specified number of months to the value of this instance. This method require to pass a parameter  The solution to fix your definition of month to 30 days, if that is acceptable. In my case it was OK, as all I did was send out notifications. tldr; If the resulting day is not a valid day in the resulting month, the last valid day of the resulting month is used Reference:

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;
    }

}

c# - How to add months to DateTime, This method is used to return a new DateTime that adds the specified number of This method does not change the value of this DateTime object. the number of days in a month, then adjusts the day part of the resulting DateTime object. C# (CSharp) System DateTime.AddMonths - 30 examples found. These are the top rated real world C# (CSharp) examples of System.DateTime.AddMonths extracted from open source projects. You can rate examples to help us improve the quality of examples.

How about like this? It solves the Jan 30th problem that would occur with the current best answer.

        public static DateTime AddJustMonths(this DateTime @this, int months)
        {
            var firstDayOfTargetMonth = new DateTime(@this.Year, @this.Month, 1).AddMonths(months);
            var lastDayofTargetMonth = DateTime.DaysInMonth(firstDayOfTargetMonth.Year, firstDayOfTargetMonth.Month);

            var targetDay = @this.Day > lastDayofTargetMonth ? lastDayofTargetMonth : @this.Day;

            return new DateTime(firstDayOfTargetMonth.Year, firstDayOfTargetMonth.Month, targetDay);
        }

DateTime.AddMonths() Method in C#, how to get the datetime of a current day in C# or VB and add one month to it Sample AddMonths(1); var StartOfMonth = new DateTime(now. of the current month to the last second of the current month which is just as easy. The second month (February) only has 28 days in 2010, so PHP auto-corrects this by just continuing to count days from February 1st. You then end up at March 3rd. How to get what you want: To get what you want is by: manually checking the next month. Then add the number of days next month has. I hope you can yourself code this.

public static DateTime NextMonth(DateTime date)
{
    DateTime nextMonth = date.AddMonths(1);

    if (date.Day != DateTime.DaysInMonth(date.Year, date.Month)) //is last day in month
    {
        //any other day then last day
        return nextMonth;
    }
    else
    {
       //last day in the month will produce the last day in the next month
       return date.AddDays(DateTime.DaysInMonth(nextMonth.Year, nextMonth.Month));
    }
}

And generalized for multiple months:

public static DateTime AddMonthToEndOfMonth(DateTime date, int numberOfMonths)
{
    DateTime nextMonth = date.AddMonths(numberOfMonths);

    if (date.Day != DateTime.DaysInMonth(date.Year, date.Month)) //is last day in month
    {
        //any other day then last day
        return nextMonth;
    }
    else
    {
        //if date was end of month, add remaining days
        int addDays = DateTime.DaysInMonth(nextMonth.Year, nextMonth.Month) - nextMonth.Day;
        return nextMonth.AddDays(addDays);
    }
}

The code is tested against February issues, leap year and New Year transition. All test passed.

[TestMethod]
public void AddMonthTest_January()
{
    for (int i = 1; i <= 28; i++)
    {
        Assert.AreEqual(new DateTime(2015, 2, i), NextMonth(new DateTime(2015, 1, i)));
    }
    Assert.AreEqual(new DateTime(2015, 2, 28), NextMonth(new DateTime(2015, 1, 29)));
    Assert.AreEqual(new DateTime(2015, 2, 28), NextMonth(new DateTime(2015, 1, 30)));
    Assert.AreEqual(new DateTime(2015, 2, 28), NextMonth(new DateTime(2015, 1, 31)));
}

[TestMethod]
public void AddMonthTest_February()
{
    Assert.AreEqual(new DateTime(2015, 3, 31), NextMonth(new DateTime(2015, 2, 28)));

    for (int i = 1; i <= 27; i++)
    {
        Assert.AreEqual(new DateTime(2015, 3, i), NextMonth(new DateTime(2015, 2, i)));
    }            
}

[TestMethod]
public void AddMonthTest_March()
{
    Assert.AreEqual(new DateTime(2015, 4, 30), NextMonth(new DateTime(2015, 3, 31)));

    for (int i = 1; i <= 30; i++)
    {
        Assert.AreEqual(new DateTime(2015, 4, i), NextMonth(new DateTime(2015, 3, i)));
    }
}

[TestMethod]
public void AddMonthTest_December()
{            
    for (int i = 1; i <= 31; i++)
    {
        Assert.AreEqual(new DateTime(2016, 1, i), NextMonth(new DateTime(2015, 12, i)));
    }
}

[TestMethod]
public void AddMonthTest_January_LeapYear()
{
    for (int i = 1; i <= 29; i++)
    {
        Assert.AreEqual(new DateTime(2016, 2, i), NextMonth(new DateTime(2016, 1, i)));
    }            
    Assert.AreEqual(new DateTime(2016, 2, 29), NextMonth(new DateTime(2016, 1, 30)));
    Assert.AreEqual(new DateTime(2016, 2, 29), NextMonth(new DateTime(2016, 1, 31)));
}

[TestMethod]
public void AddMonthTest_February_LeapYear()
{
    Assert.AreEqual(new DateTime(2016, 3, 31), NextMonth(new DateTime(2016, 2, 29)));

    for (int i = 1; i <= 28; i++)
    {
        Assert.AreEqual(new DateTime(2016, 3, i), NextMonth(new DateTime(2016, 2, i)));
    }
}

[TestMethod]
public void AddHalfYearTest_January_LeapYear()
{        
    for (int i = 1; i <= 31; i++)
    {
        Assert.AreEqual(new DateTime(2016, 7, i), new DateTime(2016, 1, i).AddMonthToEndOfMonth(6));
    }
}

[TestMethod]
public void AddHalfYearTest_February_LeapYear()
{
    Assert.AreEqual(new DateTime(2016, 8, 31), new DateTime(2016, 2, 29).AddMonthToEndOfMonth(6));

    for (int i = 1; i <= 28; i++)
    {
        Assert.AreEqual(new DateTime(2016, 8, i), new DateTime(2016, 2, i).AddMonthToEndOfMonth(6));
    }
}

[TestMethod]
public void AddHalfYearTest_December()
{
    Assert.AreEqual(new DateTime(2016, 6, 30), new DateTime(2015, 12, 31).AddMonthToEndOfMonth(6));
    for (int i = 1; i <= 30; i++)
    {
        Assert.AreEqual(new DateTime(2016, 6, i), new DateTime(2015, 12, i).AddMonthToEndOfMonth(6));
    }
}

Datetime add 1 month to current day, AddMonths is the proper way to add or subtract months to a date. If you want to subtract a given number of days, use Datetime. only 1 or 1 and 2 or 1 and 2 and 3 etc will have data, at no time can it have no data in 1 but  function Add-DateTimeMonth { <# .Synopsis Add months to the datetime object with workaround for a "february bug" .DESCRIPTION Humans have a bug in their gregorian calendar routines, when they add months (and months only) to the last day of the second month (which itself is not a fixed value in the 1/4th of times), they expect return value to be the last day of the resulting month, not a

This code will add the number of months and will jump to the last day of the target month if the current day is the last day of the current month. Note that there is fundamentally no solution to the problem of January 30 without doing fully custom dates:

If the date is the only state, then no matter how you handle the one month jump ahead from January 30, you have to chose if you interpret the result as the last day of February or simply the 28th of the current month. You can't have both since the date is your only state. There is no 'flag' which tells you that this very 28th of February was originally the single to last day in January.

Effectively this means that Jan30.AddMonthsCustom(1).AddMonthsCustom(1) != Jan30.AddMonthsCustom(2) and that eventually any 30th, 29th and 28th date ends up on the last day of the month if you keep propagating.

public static DateTime AddMonthsCustom(this DateTime date, int months)
{

    // Check if we are done quickly.
    if(months == 0)
        return;

    // Lookup the target month and its last day.
    var targetMonth = new DateTime(date.Year, date.Month, 1).AddMonths(months);
    var lastDay = DateTime.DaysInMonth(targetMonth.Year, targetMonth.Month);

    // If we are starting out on the last day of the current month, then jump
    // to the last day of the target month.
    if (date.Day == DateTime.DaysInMonth(date.Year, date.Month))
        return new DateTime(targetMonth.Year, targetMonth.Month, lastDay);

    // If the target month cannot accomodate the current day, jump to the 
    // last day of the target month.
    if (date.Day > lastDay)
        return new DateTime(targetMonth.Year, targetMonth.Month, lastDay);

    // Simply jump to the current day in the target month.
    return new DateTime(targetMonth.Year, targetMonth.Month, date.Day);
}

If I am however wrong, please let me know. I really would like to have this solved.

Whats a stable type-safe way to subtract 6 Months from any date , Learn more about datetime month addition. 191 views (last 30 days) If I have a datetime value of today, can I add 3 or 6 months to that value without splitting does not work in its current command form using a values name but only now. Adding months to a date We can add months to a date like below. C# will take care of year when you add the months since it adheres to universal date and time rules.

Adding month values to datetime function, DateTime::add -- date_add — Adds an amount of days, months, years, hours, minutes and (Only a side note on procedural style mentions it, but it obviously does not apply to Extends DateTime to include a sensible addMonth method. In this article we will discuss on How to add Days, Weeks, Months, Quarters or Years to a Date in Sql Server? You may also like to read the following other popular articles on Date and Time in Sql Server: How to get Date Part only from DateTime in Sql Server; How to get Day, Month and Year Part from DateTime in Sql Server

DateTime::add - Manual, Procedural style only: A DateTime object returned by date_create(). into a Unix timestamp; DateTime::add() - Adds an amount of days, months, years, hours, 2017-01-30 past end of feb, but not dec function addMonths($date,$months){ Remarks. The day part of the resulting DateTime is affected if the resulting day is not a valid day in the resulting month of the resulting year. In this case, the day part is changed to the last valid day in the resulting month of the resulting year. The year part of the resulting DateTime is affected if the resulting month is outside

DateTime::modify - Manual, We can add months to a date like below. C# will take care of year when you add the months since it adheres to universal date and time rules. The day will  Hi Geeta, i had a query how do we add months to a date if its in decimal. example adding 0.5 months or 1.5 months i tried and its getting truncated. can you pls suggest. below is my current query but when i add 0.5 months to a date its converting its not adding the days for 0.5 months to the date. its adding 0 only.

Comments
  • If any answer meets your needs please hit the "tick" next to it to accept it.
  • To finetune the algorithm: And what do you expect when the date is 27 february or 1 february?
  • Clever - that would work if he's guaranteed to have the last day of the month already.
  • If he doesn't, the result is the same as AddMonths(1)
  • For the 30th of January, it isn't.
  • Any solution for the the 30th of January?
  • Why not just new Date(date.Year, date.Month, 1).AddMonths(1).AddDays(-1) in else?
  • Yeah, the last day of the months would suffice as well I think...Ill mark the answer as soon as it works :)
  • What if your date is in december?
  • @Philippe Leybaert: Thanks for spotting that out. check my edit.
  • If you mean set the day property - it is immutable (this is C# - see the tags on the question).
  • Woah! Sorry. I didn't realise you couldn't do that in C#.