Subtract days from DateTime

I have the following code in my C # program.

DateTime dateForButton = DateTime.Now; dateForButton = dateForButton.AddDays(-1); // ERROR: un-representable DateTime 

Whenever I run it, I get the following error:

An added or subtracted value results in an unrepresentable DateTime.
Parameter Name: Value

I have never seen this error message before, and I donโ€™t understand why I see it. From the answers that I read so far, I believe that I can use -1 in the addition operation to subtract days, but as my question shows, this is not the case when I try to do it.

+104
c # datetime
Jun 22 '12 at 7:33
source share
8 answers

This error usually occurs when trying to subtract an interval from DateTime.MinValue or you want to add something to DateTime.MaxValue (or you are trying to create a date outside this min-max interval). Are you sure you are not using MinValue anywhere?

+61
Jun 22 2018-12-12T00:
source share
 DateTime dateForButton = DateTime.Now.AddDays(-1); 
+228
Jun 22 2018-12-12T00:
source share

You can do:

 DateTime.Today.AddDays(-1) 
+35
Oct 31 '14 at 12:17
source share

You can use the following code:

 dateForButton = dateForButton.Subtract(TimeSpan.FromDays(1)); 
+29
Jun 22 2018-12-12T00:
source share

The object (i.e., target variable) for the AddDays method cannot be the same as the source.

Instead:

 DateTime today = DateTime.Today; today.AddDays(-7); 

Try this instead:

 DateTime today = DateTime.Today; DateTime sevenDaysEarlier = today.AddDays(-7); 
+3
Aug 02 '16 at 17:25
source share

I had problems using AddDays (-1).

My solution is TimeSpan .

 DateTime.Now - TimeSpan.FromDays(1); 
+1
Jul 18 '18 at 15:28
source share

dateTime.AddDays(-1) does not subtract this one day from the link for dateTime . It will return a new instance with one day subtracted from the original link.

 DateTime dateTime = DateTime.Now; DateTime otherDateTime = dateTime.AddDays(-1); 
0
Nov 17 '16 at 12:32
source share

Using AddDays(-1) worked for me until I tried to cross the months. When I tried to subtract 2 days from 2017-01-01, the result was 2016-00-30. He could not adjust the month correctly (although the year seemed to be fine).

I used date = Convert.ToDateTime(date).Subtract(TimeSpan.FromDays(2)).ToString("yyyy-mm-dd"); and no problem.

0
Feb 09 '17 at 13:37 on
source share



All Articles