MVC 视图中的日期格式

Date formatting in MVC view

我在 mvc 模型中有以下实体:

[Display(Name = "Date Of Birth")]
public DateTime? DateOfBirth { get; set; }

我在以下视图中使用它:

<td title="@u.CreatedDate">
    @if (@u.DateOfBirth != null)
    {
        @u.DateOfBirth
    }
</td>

这是一段有效的代码,但我想以 dd/mm/yyyy 格式显示此日期。

我试过这样的方法:

1. string.Format("dd/MM/yyyy", u.DateOfBirth);

2.  [Display(Name = "Date Of Birth")]
    [DisplayFormat (DataFormatString="dd/MM/yyyy")]
    public DateTime? DateOfBirth { get; set; }

但对我来说没有任何效果。请帮助

您可以使用 3 个选项

@Html.DisplayFor(m => u.DateOfBirth) // assumes you have [DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]

@String.Format("{0:dd/MM/yyyy}", u.DateOfBirth)

@u.DateOfBirth.Value.ToString("dd/MM/yyyy")

前2种情况不需要@if (@u.DateOfBirth != null)检查