Remove an N amount of days on a date

Asked

Viewed 674 times

7

How to remove an amount of N days in a date ?

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

2 answers

8


There is no method of subtraction, but just use a mathematical trick with the method 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);
        }
    }
}

Behold working ideone. And in the .NET Fiddle. Also put on the 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.

5

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.