Subtract days from a DateTime

后端 未结 9 444
北海茫月
北海茫月 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: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.

提交回复
热议问题