Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Adding months to a date in C#

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 remain same.

  1. using System;
  2.  
  3. namespace forgetCode
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9.  
  10. Console.WriteLine("Enter year in the format dd-mm-yyyy");
  11. DateTime dt = Convert.ToDateTime(Console.ReadLine());
  12.  
  13. Console.WriteLine("Enter the months to add :");
  14. int months = Convert.ToInt32(Console.ReadLine());
  15.  
  16. DateTime newDate = dt.AddMonths(months);
  17. Console.WriteLine(newDate.ToShortDateString());
  18. }
  19.  
  20. }
  21. }


  1. Output:
  2. Enter year in the format dd-mm-yyyy
  3. 02-03-2012
  4. Enter the months to add :
  5. 4
  6. 02-07-2012
  7.  
  8.  
  9. Enter year in the format dd-mm-yyyy
  10. 20-11-2012
  11. Enter the months to add :
  12. 2
  13. 20-01-2013
  14.  
  15. ..