Subtract days from a DateTime

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

    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?

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

    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.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题