ASP.. NET MVC显示日期而不显示时间

本文关键字:显示 时间 日期 MVC ASP NET | 更新日期: 2023-09-27 18:01:31

我用以下方式装饰了我的模型字段:

[DataType(DataType.Date)]
[Display(Name = "Date of birth")]
public string DateOfBirth { get; set; }

当我想使用以下代码在视图中显示值时:

<%: Html.DisplayFor(m => m.DateOfBirth) %>

问题是日期与时间值一起显示。我想知道为什么它不考虑DateType属性,只显示日期值而不显示时间。我知道我可以为DateTime创建一个显示模板,但在其他情况下,除了出生日期,我还想同时显示时间和日期。如何解决这个问题?

ASP.. NET MVC显示日期而不显示时间

这里的问题是您使用的是字符串值而不是DateTime。

将你的模型改为:

[DataType(DataType.Date)]
[Display(Name = "Date of birth")]
public DateTime? DateOfBirth { get; set; }

DataType只有当它是DateTime类型时才会起作用,您还可以获得额外的优势,当使用DateTime时,它将自动将其验证为有效日期。如果使用string,则必须使用正则表达式验证器来确保输入了正确的日期。

编辑模式和显示

 [DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:MM/dd/yyyy}")]

虽然如果只是显示,这可能行得通

[DisplayFormat(DataFormatString = "{0:d}")]

使用DisplayFormatAttribute来指定显示值时的格式。同样,你可以创建两个DisplayTemplates, Date和DateTime,并使用UIHintAttribute来指定模板

您可以使用ToShortDateString()或ToLongDateString()来只显示日期,例如:

@Model.EventDate.ToShortDateString()
@Model.EventDate.ToLongDateString()

如果您的日期是DateTime类型,并且ToShortDateString()ToLongDateString()仍然不起作用,检查您的DateTime是否为空(DateTime?)。让它不可为空可以达到这个目的。

如果您正在使用MVC,也许您可以在您的客户端脚本上尝试:

@{
      string birthDateOnly = Model.DateOfBirth.Date.ToShortDateString();
 }
@Html.DisplayTextFor(m => birthDateOnly)

使用@Value和ToShortDateString()可以只显示日期。

@Html.TextBoxFor(model => model.StartDate, "", new { id = "date", @class = "datepicker", @style = "width:70%; height:30px;", @placeholder = "Enter Date", @Value = @Model.StartDate.ToShortDateString()})