C# 使用.AddMonths(-1)减去DateTime月份没有任何作用?
这是我的代码,我不明白为什么它不起作用。这是从我自己的代码库中的文本副本;代码中的其他地方不应存在隐藏的复杂性C# 使用.AddMonths(-1)减去DateTime月份没有任何作用?,c#,datetime,C#,Datetime,这是我的代码,我不明白为什么它不起作用。这是从我自己的代码库中的文本副本;代码中的其他地方不应存在隐藏的复杂性[edit]。这意味着这应该有效。我错过了什么 DateTime billDate = new DateTime(2020, 3, 1); // March 1st, 2020 MessageBox.Show($"billdate month {billDate.Month}"); // billdate month 3 billDate.AddMonths
[edit]。这意味着这应该有效。我错过了什么
DateTime billDate = new DateTime(2020, 3, 1); // March 1st, 2020
MessageBox.Show($"billdate month {billDate.Month}"); // billdate month 3
billDate.AddMonths(-1); // subtract a month
MessageBox.Show($"month after change {billDate.Month}"); // month after change 3
我预计这个月将减少到2个月。为什么不呢?返回一个新的DateTime
对象;它不会改变现有的。尝试:
billDate = billDate.AddMonths(-1);
您必须引用文档:返回一个新的日期时间,将指定的月数添加到此实例的值。实际上,DateTime
是不可变的。