在 Session["DateOfBirth"] Asp.NET MVC 中仅显示日期

Display only date in Session["DateOfBirth"] Asp.NET MVC

Session["DateOfBirth"] 正在从数据库中收集日期时间(SQL 使用 Entity Framework)但我只想显示日期而不是时间。

这是我的代码:

查看模型class:

[Display(Name = "Date of Birth")]
[Required(ErrorMessage = "Date of Birth required")]
[DataType(DataType.Date)]
public string dob { get; set; }

控制器class:

Session["dob"] = umail.u_dob;

索引视图:

<div class="col">
  <h6>Date of Birth</h6>
  <p class=" ">@Session["dob"]</p>
</div>

输出画面:

您可以通过转换 Session 变量来使用 ToShortDateString():

Convert.ToDateTime(Session["dob"].ToString()).ToShortDateString()

另一种选择是在您的视图模型中创建一个新的 属性 仅供查看:

[Display(Name = "Date of Birth")]
[Required(ErrorMessage = "Date of Birth required")]
[DataType(DataType.Date)]
public string dob {
  get;
  set;
}

[Display(Name = "Date of Birth")]
public string formattedDob {
  get {
    DateTime dateResult;
    
    if (DateTime.TryParse(dob, out dateResult)) {
      return dateResult.ToShortDateString();
    }
    
    return "";
  }
}

在控制器中试试这个:

Session["dob"] = umail.u_dob.ToString("MM/dd/yyyy");

以下代码适用于我的情况。 在控制器中使用此代码

Session["dob"] = Convert.ToDateTime(Session["dob"].ToString()).ToShortDateString();