Introducing Radical.sh

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

Subtracting months from a date in C#

We can subtract months from a date like below.
C# will take care of year when you subtract 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 subtract :");
  14. int months = Convert.ToInt32(Console.ReadLine());
  15.  
  16. DateTime newDate = dt.AddMonths(-months);
  17. Console.WriteLine(newDate.ToShortDateString());
  18. }
  19.  
  20. }
  21. }


Output:
Enter year in the format dd-mm-yyyy
02-02-2012
Enter the months to subtract :
4
02-10-2011

..