Remove a quantity N of days on a date

2

How can I remove a quantity of N days on a date?

Example:

namespace TesteData
{
  class Program
   {
    static void Main(string[] args)
    {
        var dataAtual = DateTime.Now.Date; // dataAtual 13/09/17
        var qtdDias = 5;

        //Como fazer essa dataAtual 13/09/17 - qtdDias = 08/09/17
        //dataAtual = 08/09/17
      }
    }
}
    
asked by anonymous 13.09.2017 / 22:25

2 answers

6

It does not have a subtraction method, but just use a mathematical trique with the AddDays() :

using System;

namespace TesteData {
    public class Program {
        public static void Main(string[] args) {
            var dataAtual = DateTime.Now.Date;
            var qtdDias = 5;
            var novaData = dataAtual.AddDays(-qtdDias);
            Console.WriteLine(novaData);
        }
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I put it in GitHub for future reference .

  

To subtract a particular time interval from the current instance, call the method that adds that time interval to the current date, and supply a negative value as the method argument. For example, to subtract two months from the current date, call the AddMonths (Int32) method with a value of -2.

Documentation .

    
13.09.2017 / 22:27
4

simply:

namespace TesteData
{
  class Program
   {
    static void Main(string[] args)
    {
        var qtdDias = 5;
        var dataAtual = DateTime.Now.Date.AddDays(qtdDias*-1); // dataAtual 13/09/17
      }
    }
}
    
13.09.2017 / 22:27