从日期时间中减去天数

我的C#程序中有以下代码。

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

每当我运行它时,都会出现以下错误:

添加或减去的值将导致无法表示的DateTime.
参数名称:值

我以前从未见过这个错误消息,也不明白为什么我会看到它。从我目前读到的答案来看,我相信我可以在加法运算中使用-1来减去天数,但正如我的问题所显示的,这不是我正在尝试做的事情。

415353 次浏览

You can use the following code:

dateForButton = dateForButton.Subtract(TimeSpan.FromDays(1));

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?

DateTime dateForButton = DateTime.Now.AddDays(-1);

You can do:

DateTime.Today.AddDays(-1)

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);

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);

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.

I've had issues using AddDays(-1).

My solution is TimeSpan.

DateTime.Now - TimeSpan.FromDays(1);

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.