2014-03-07 47 views
1

所有我想要的是在asp.net MVC控制器转换07.03.2014到2014-03-07,dd.mm.yyyyyyyy-mm-dd;)谢谢。转换c#日期时间输入[类型=日期]

+0

http://www.csharp-examples.net/string-format-datetime/ –

+0

请只与特定的标记您的问题版本号,如果你的问题实际上取决于版本。 –

+0

好吧,我会的。 ;) – Dimitri

回答

4

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

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

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

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

+0

非常感谢;) – Dimitri

2
使用

我用来创建一个编辑器模板来处理DataTime & Nullable<DateTime>就像下面一样

Views/S hared/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"}) 
+0

超级有用,谢谢。小事:我注意到dateFormat在第4行被声明,但根本没有被使用? –