Subtract days from a DateTime

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

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

提交回复
热议问题