I have a dropdownlist called ddlPayrollDate in my asp.net web site. I want to insert/bound dates 2 and 17 of last 3 months, including the current month. To consider when a year is changed, I had to write multiple conditions in my C# code which is given below is my code:
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)));
Is there a way I can optimize this code without having these many conditions by using any datetime functions. Thanks in advance!
It seems to me that you want a loop. Something like:
This assumes that you always want the 17th and the 2nd of the current month (in UTC), whether the current day of month is before the 2nd, between the 2nd and the 17th, or after the 17th.
Also note that you should usually use the invariant culture when specifying a custom date format; or use a standard date format with a “normal” culture.