I have the following code in my C# program.
DateTime dateForButton = DateTime.Now;
dateForButton = dateForButton.AddDays(-1); // ERROR: un-representable Date
That error usually occurs when you try to subtract an interval from DateTime.MinValue
or you want to add something to DateTime.MaxValue
(or you try to instantiate a date outside this min-max interval). Are you sure you're not assigning MinValue
somewhere?
Instead of directly decreasing number of days from the date object directly, first get date value then subtract days. See below example:
DateTime SevenDaysFromEndDate = someDate.Value.AddDays(-1);
Here, someDate is a variable of type DateTime.
The object (i.e. destination variable) for the AddDays method can't be the same as the source.
Instead of:
DateTime today = DateTime.Today;
today.AddDays(-7);
Try this instead:
DateTime today = DateTime.Today;
DateTime sevenDaysEarlier = today.AddDays(-7);