闰年导致Blazor到期日计算器后续年份计算错误求助
修复Blazor到期日计算器的闰年计算问题
问题分析
你的代码存在两个核心问题,直接导致了闰年后续年份的计算错误:
- 第一个分支中计算了当月月末日期
endOfMonth,但未将其赋值给ExpiryDate.Value,如果需求是将到期日设为目标日期所在月的最后一天,这会导致关键逻辑缺失,跨闰年时月末天数不一致的问题就会暴露。 - 条件判断存在冗余,两个
if分支互斥,可优化为if-else结构,提升代码可读性。
修复后的代码
@code { private RecordEditContext recordEditContext = new RecordEditContext(new()); private ExpirationDate ExpiryDate = new ExpirationDate(); private string errorMessage = string.Empty; private bool IsError => this.errorMessage != string.Empty; private void CalculateExpiryDate() { this.errorMessage = string.Empty; this.ExpiryDate.Value = DateTime.MinValue; this.recordEditContext.SetToClean(); if (!recordEditContext.IsBeforeDate && !recordEditContext.IsPlate && recordEditContext.ShelfLife >= 90) { // 计算保质期结束前30天的临时日期 DateTime tempExpDate = recordEditContext.MixDate.AddDays(recordEditContext.ShelfLife).AddDays(-30); // 将到期日设置为临时日期所在月份的最后一天 this.ExpiryDate.Value = new DateTime(tempExpDate.Year, tempExpDate.Month, DateTime.DaysInMonth(tempExpDate.Year, tempExpDate.Month)); this.ExpiryDate.Format = ExpirationDate.ExpiryDateFormat.MonthYear; return; } else if (recordEditContext.IsBeforeDate || recordEditContext.IsPlate || recordEditContext.ShelfLife < 90) { this.ExpiryDate.Value = recordEditContext.MixDate.AddDays(recordEditContext.ShelfLife).AddDays(-1); this.ExpiryDate.Format = ExpirationDate.ExpiryDateFormat.YearMonthDay; return; } this.errorMessage = "Please Try Again. Information Not Satisfactory."; } }
关键优化说明
- 直接使用
DateTime.AddDays替代TimeSpan.FromDays的组合,代码更简洁且逻辑一致,DateTime类本身会自动处理闰年、月末天数等日期计算细节。 - 确保在保质期≥90天的分支中,正确将到期日设置为目标月份的最后一天,彻底解决跨闰年时月末天数不同导致的计算偏差。
- 如果你的需求并非取月末,而是直接使用「保质期结束前30天」的原始日期,需要检查
MixDate的赋值逻辑,避免手动构造日期时出现硬编码2月29日到非闰年的错误。
内容的提问来源于stack exchange,提问作者Sahar
相关产品推荐
相关产品推荐

