In my C# program, I have the following code.
DateTime dateForButton = DateTime.Now; dateForButton = dateForButton.AddDays(-1); // ERROR: un-representable DateTime
I receive the following error whenever I run it:
This is the first time I’ve seen this error notice, and I’m not sure why. I’m led to believe that I can use -1 in an add operation to subtract days based on the responses I’ve read so far, but this is not the case for what I’m trying to achieve, as my question demonstrates.
Asked by Buena
DateTime dateForButton = DateTime.Now.AddDays(-1);
Answered by Christian Phillips
When you try to remove an interval from DateTime, you frequently get this error. If you wish to add something to DateTime, use MinValue. MaximumValue (or you try to instantiate a date outside this min-max interval). Are you sure you don’t have MinValue assigned somewhere?
Answered by CyberDude
You can do:
Answered by sam
The following code can be used:
dateForButton = dateForButton.Subtract(TimeSpan.FromDays(1));
Answered by Rajesh Subramanian
The dateTime.AddDays(-1) method does not remove that one day from the referenced dateTime. It will create a new instance, subtracting that one day from the original reference.
DateTime dateTime = DateTime.Now; DateTime otherDateTime = dateTime.AddDays(-1);
Answered by cahit beyaz
Post is based on https://stackoverflow.com/questions/11151976/subtract-days-from-a-datetime