I have the following code in my C# program.
DateTime dateForButton = DateTime.Now;
dateForButton = dateForButton.AddDays(-1); // ERROR: un-representable Date
The dateTime.AddDays(-1)
does not subtract that one day from the dateTime
reference. It will return a new instance, with that one day subtracted from the original reference.
DateTime dateTime = DateTime.Now;
DateTime otherDateTime = dateTime.AddDays(-1);
You can do:
DateTime.Today.AddDays(-1)
I've had issues using AddDays(-1).
My solution is TimeSpan.
DateTime.Now - TimeSpan.FromDays(1);
DateTime dateForButton = DateTime.Now.AddDays(-1);
Using AddDays(-1)
worked for me until I tried to cross months. When I tried to subtract 2 days from 2017-01-01 the result was 2016-00-30. It could not handle the month change correctly (though the year seemed to be fine).
I used date = Convert.ToDateTime(date).Subtract(TimeSpan.FromDays(2)).ToString("yyyy-mm-dd");
and have no issues.
You can use the following code:
dateForButton = dateForButton.Subtract(TimeSpan.FromDays(1));