将c#Datetime转换为输入[type = date]

时间:2014-03-07 15:23:44

标签: asp.net-mvc date datetime

我想要的是在asp.net MVC控制器中将07.03.2014转换为2014-03-07,dd.mm.yyyy转换为yyyy-mm-dd;)谢谢。

2 个答案:

答案 0 :(得分:4)

您可以在DateTime对象上使用ToString()方法来获取所需的格式。

DateTime dt=new DateTime(2014,03,07);
string newDateFormatted= dt.ToString("yyyy-MM-dd");

如果您想从字符串加载日期时间对象,可以尝试使用DateTime.ParseDateTime.ParseExtractTryParse

Here是一个很好的格式说明符列表,可以与ToString()

一起使用

答案 1 :(得分:2)

我曾经创建了一个编辑模板,可以使用DataTime & Nullable<DateTime>,如下所示

<强>查看/共享/ EditorTemplates / CustomDateTime.cshtml

@model DateTime?
@{
    String modelValue = "";
    var dateFormat =
             System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;


    if (Model.HasValue)
    {
        if (Model.Value != DateTime.MinValue)
        {
            if (ViewData["_displayFormat"] != null)
            {
             var format=(string)ViewData["_displayFormat"];
              modelValue = Model.Value.ToString(format)

            } 
            else{
            modelValue = Model.Value.ToShortDateString();
            }
        }
    }
}

    @Html.TextBox("", modelValue)

在视图中

 @Html.EditorFor(m => m.DateOfBirth, "CustomDateTime", 
                  new { _displayFormat= "yyyy-MM-dd"})