首页 > 解决方案 > 如何为 html 表的日期列提供日期格式 dd/mm/yyyy

问题描述

我正在寻找如何为表格的日期列提供“dd/mm/yyyy”格式

[DataType(DataType.Date, ErrorMessage = "Date only")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
public string FromDate { get; set; }

<td>@Html.TextBoxFor(model => model.FromDate, new { @class = "form-control date-input emphrs" })</td>

标签: c#htmlasp.net-corerazor-pages

解决方案


你可以这样试试:

模型:

 public class DateFormaterModel
    {
        [DataType(DataType.Date, ErrorMessage = "Date only")]
        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
        public string FromDate { get; set; }

        [DataType(DataType.Date, ErrorMessage = "Date only")]
        [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
        public string ToDate { get; set; }
    }

控制器:

public IActionResult DateFormatter()
        {
            return View();
        }

看法:

@model MVCApps.Models.DateFormaterModel

@{
    ViewData["Title"] = "DateFormatter";
}

<h2>Date Formatter</h2>

<table id="tblEntry" class="table table-striped">
    <thead>
        <tr>
            <th>Date From</th>
            <th>Date To</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>@Html.EditorFor(model => model.FromDate, new { @id = "fromDate", htmlAttributes = new { @class = "form-control datepicker w-100"} })</td>
            <td>@Html.EditorFor(model => model.ToDate, new { @id = "toDate", htmlAttributes = new { @class = "form-control datepicker w-100" } })</td>
        </tr>

    </tbody>
</table>

输出:

在此处输入图像描述

注意:您错过了ApplyFormatInEditMode = true有助于实现这一目标的这个属性。此外,正如@LIama已经说过string那样,不会在这里采取相应的行动。所以DateTime将是相同的。但string也可以按照我向您展示的方式完美运行。

希望它能帮助您解决问题。


推荐阅读