简体   繁体   English

Asp.Net MVC 5日期格式

[英]Asp.Net MVC 5 Date format

I am only trying to return the date in my MVC application and have come across a problem. 我只是想在我的MVC应用程序中返回日期,并且遇到了问题。 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 我已将我的模型DataFormatString = "{0:dd/M/yy}"应用于模型,并且还根据这些帖子的建议包含了ApplyFormatInEditMode = true ,这些ASP.NET MVC显示日期而不 显示 时间仅显示日期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 . 但是,我正在生成该字段以将接下来的5周开始日期(如此处所示)包括在下拉列表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 我该如何删除时间以仅显示日期

you need to set text and value in SelectList . 您需要在SelectList设置textvalue

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. SelectedDate是模型中的DateTime属性。

Esiprogrammer answer will work well, if you wanted to parse the date, this will be another option. Esiprogrammer答案会很好用,如果您想解析日期,这将是另一个选择。 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. 将该属性放在模型上将不起作用,因为您没有使用模型显示日期,而是使用viewdata显示日期。

After you add a date and within your if condition add this: listDates[i] = ParseDate(DateTime.Today.ToString(), "MM/dd/yy"); 添加日期后,在if条件下添加以下内容: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 从此线程在MVC中的@ Html.DisplayFor()中仅显示日期的地方添加顶部答案帮助程序类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM