我的 asp.net 网站中有一个名为 ddlPayrollDate 的下拉列表。我想插入/绑定最近 3 个月的日期 2 和 17,包括当月。要考虑何时更改年份,我必须在我的 C# 代码中编写多个条件,下面给出的是我的代码:
ddlPayrollDate.Items.Insert(1, String.Format("{0:MMMM dd, yyyy}", new DateTime (DateTime.UtcNow.Year, DateTime.UtcNow.Month, 17)));
ddlPayrollDate.Items.Insert(2, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 2)));
if (DateTime.UtcNow.Month != 1)
ddlPayrollDate.Items.Insert(3, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month - 1, 17)));
else
ddlPayrollDate.Items.Insert(3, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year - 1, 12, 17)));
if (DateTime.UtcNow.Month != 1)
ddlPayrollDate.Items.Insert(4, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month - 1, 2)));
else
ddlPayrollDate.Items.Insert(4, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year - 1, 12, 2)));
if (DateTime.UtcNow.Month != 1 && DateTime.UtcNow.Month != 2)
ddlPayrollDate.Items.Insert(5, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month - 2, 17)));
else if (DateTime.UtcNow.Month == 1)
ddlPayrollDate.Items.Insert(5, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year - 1, 11, 17)));
else
ddlPayrollDate.Items.Insert(5, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year - 1, 12, 17)));
if (DateTime.UtcNow.Month != 1 && DateTime.UtcNow.Month != 2)
ddlPayrollDate.Items.Insert(6, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month - 2, 2)));
else if (DateTime.UtcNow.Month == 1)
ddlPayrollDate.Items.Insert(6, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year - 1, 11, 2)));
else
ddlPayrollDate.Items.Insert(6, String.Format("{0:MMMM dd, yyyy}", new DateTime(DateTime.UtcNow.Year - 1, 12, 2)));
有没有一种方法可以通过使用任何日期时间函数来优化此代码而无需满足这些条件。提前致谢!