1

I want to add one month to the DateTime object but this object format is "dd/MM/yyyy" When I add one month it increases one day, but this is not what I need.

Here is the code.

DateTime installmentdate = baseDate.AddMonths(1);

Suppose baseDate is 10/2/2014 when I add one month to date it becomes 10/3/2014 Please suggest me how to do it.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
Datta
  • 819
  • 3
  • 14
  • 27

4 Answers4

3

Your code is correct , your date format is dd/MM/yyyy , adding one month to

 dd/MM/yyyy
 10/02/2014

become

 dd/MM/yyyy
 10/03/2014

You can change your format to MM/dd/yyyy for your need !

zey
  • 5,939
  • 14
  • 56
  • 110
3

you can change the dateformat and after that apply .AddMonths() method.

DateTime installmentDate=Convert.toDateTime(baseDate.tostring("MM/dd/yyyy")).AddMonths(1);
Ravi Verma
  • 182
  • 1
  • 3
  • 12
3

DateTime doesn't have any format, you need to control the format where you display it using the MM\dd\yyyy format for its string representation.

.AddMonths does exactly what it says, so DateTime installmentdate = baseDate.AddMonths(1); is correct way and the DateTime incremented by 1 month is assigned to installmentdate

you only have to format the part where you display installmentdate

V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
0

Nothing is wrong with your code, you are just having problem with the parsing of baseDate,

Your baseDate calculation should be something like,

    CultureInfo provider = CultureInfo.InvariantCulture;
    DateTime baseDate = DateTime.ParseExact(yourDateInString, "dd/MM/yyyy", provider);

And then you can continue with your above code, which is

DateTime installmentdate = baseDate.AddMonths(1);
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58