Bind Dropdown List Between Two Dates in DD MMM Format

Bind Dropdown List Between Two Dates in DD MMM  Format

var Startdate = System.DateTime.Now; 

var lastDate = Startdate.AddDays(30);

List Collection For the Store List of Dates

List<SelectListItem> listDate = new List<SelectListItem>();

For Loop For the Add Dates in SelectListItem with Suffix

for (DateTime date = Startdate; date <= lastDate; date = date.AddDays(1))
{
            int day1 = date.Day;
            int month1 = date.Month;
            string dtDate = GetDaySuffix(day1) + " " + GetMonthString(month1);
     listDate.Add(new SelectListItem { Value = dtDate, Text = dtDate });
              
 }

model.DateList = listDate;

Method to Get Day With Suffix
       private string GetDaySuffix(int day)
        {
            string postfix = "th";
            if (day == 1 || day == 21 || day == 31)
            {
                postfix = "st";
            }
            else if (day == 2 || day == 22)
            {
                postfix = "nd";
            }
            else if (day == 3 || day == 23)
            {
                postfix = "rd";
            }
            return day.ToString() + postfix;
        }

Method to Get Month in Full Name From Month Number

        private string GetMonthString(int month)
        {
            string monthtext = string.Empty;
            switch (month)
            {
                case 1:
                    monthtext = "January";
                    break;

                case 2:
                    monthtext = "February";
                    break;

                case 3:
                    monthtext = "March";
                    break;

                case 4:
                    monthtext = "April";
                    break;

                case 5:
                    monthtext = "May";
                    break;

                case 6:
                    monthtext = "June";
                    break;

                case 7:
                    monthtext = "July";
                    break;

                case 8:
                    monthtext = "August";
                    break;

                case 9:
                    monthtext = "September";
                    break;

                case 10:
                    monthtext = "October";
                    break;

                case 11:
                    monthtext = "November";
                    break;

                case 12:
                    monthtext = "December";
                    break;

            }
            return monthtext;
        }

View Side code

@Html.DropDownListFor(m => m.SelectedStartDate, Model.DateList, new { @class = "form-control" })

Comments

Popular posts from this blog

Validate Mobile Number with 10 Digits in ASP.Net