Subtract days from a DateTime

后端 未结 9 457
北海茫月
北海茫月 2021-01-30 04:59

I have the following code in my C# program.

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


        
相关标签:
9条回答
  • 2021-01-30 05:13

    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);
    
    0 讨论(0)
  • 2021-01-30 05:14

    You can do:

    DateTime.Today.AddDays(-1)
    
    0 讨论(0)
  • 2021-01-30 05:19

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

    My solution is TimeSpan.

    DateTime.Now - TimeSpan.FromDays(1);
    
    0 讨论(0)
  • 2021-01-30 05:22
    DateTime dateForButton = DateTime.Now.AddDays(-1);
    
    0 讨论(0)
  • 2021-01-30 05:27

    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.

    0 讨论(0)
  • 2021-01-30 05:30

    You can use the following code:

    dateForButton = dateForButton.Subtract(TimeSpan.FromDays(1));
    
    0 讨论(0)
提交回复
热议问题