0

I am only trying to return the date in my MVC application and have come across a problem. I have applied to my model DataFormatString = "{0:dd/M/yy}" and have also included ApplyFormatInEditMode = true as suggested from these posts ASP.NET MVC displaying date without time and Displaying Date only MVC

I am however generating the field to include the next 5 week commencing dates as shown here into a dropdownlist http://prntscr.com/ak825u.

This is done through the following code

  // GET: TimeSheets/Create
    public ActionResult Create()
    {

        int weekCount = 5;
        List<DateTime> listDates = new List<DateTime>();

        for (int i = 0; i < (weekCount * 7); ++i) //Get next 5 weeks
        {
            //Adds only next 5 mondays to the list of dates
            if (DateTime.Today.AddDays(i).DayOfWeek == DayOfWeek.Monday)
                listDates.Add(DateTime.Today.AddDays(i));
        }

        ViewData["DateList"] = new SelectList(listDates);

        return View();
    }

How would I go about removing the time to just display the date

1
  • It depends on what kind of web control you are using. .NET has no problem, but rendering is browser's responsibility. Alternately, you may populate a list of string instead of DateTime. Commented Mar 26, 2016 at 11:47

2 Answers 2

1

you need to set text and value in SelectList.

ViewData["DateList"] = new SelectList(listDates.Select(c => new SelectListItem() { Text = c.ToString("dd/mm/yy"), Value = c }));

in your View:

@Html.DropDownListFor(m => m.SelectedDate, (SelectList)ViewData["DateList"], "Select a date")

SelectedDate is a DateTime property in your model.

Sign up to request clarification or add additional context in comments.

2 Comments

Is dd/m/yy valid? Shouldnt it be dd/mm/yy?
yes, you're right, to remove the time part should be 'dd/mm/yy'. I edited the answer.
0

Esiprogrammer answer will work well, if you wanted to parse the date, this will be another option. Putting that attribute on your model wont work because you arent using the model to display the date, you are using viewdata to display the dates.

After you add a date and within your if condition add this: listDates[i] = ParseDate(DateTime.Today.ToString(), "MM/dd/yy");

Add the top answer helper class from this thread somewhere Display only Date in @Html.DisplayFor() in MVC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.