2011-01-13 204 views
77

以下哪項出錯?使用剃鬚刀轉換DateTime格式

@Convert.ToDateTime((@item.Date.ToShortDateString())," dd - M - yy") 

@ item.Date是顯示2005-11-15 12:00我要顯示2011年11月20

+1

組合:HTTP:// msdn.microsoft.com/en-us/library/8kb3ddd4.aspx – 2013-05-15 07:59:22

回答

207

嘗試:

@item.Date.ToString("dd MMM yyyy") 

,或者您可以使用[DisplayFormat]屬性您的視圖模型:

[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")] 
public DateTime Date { get; set } 

,並在你看來簡單:

@Html.DisplayFor(x => x.Date) 
+3

我試圖用文本框,不幸它沒有工作。有沒有辦法做到這一點的文本框? – Tobias 2011-07-12 11:08:11

+2

對於文本框,只需使用EditorFor而不是DisplayFor – 2011-07-22 21:03:44

+6

如果要將日期格式應用於EditorFor()元素,請記住在DisplayFormat定義中設置「ApplyFormatInEditMode = true」。 – Latedeveloper 2011-10-22 10:47:45

2

一般來說,書面月轉義爲MMM,4位數的年份爲yyyy,讓您的格式字符串應該像 「DD MMM YYYY」

DateTime.ToString("dd MMM yyyy") 
54

這是解決方案:

@item.Published.Value.ToString("dd. MM. yyyy") 

之前的ToString()使用價值

18

[DisplayFormat]屬性僅用於EditorFor/DisplayFor,而不是TextBoxFor等原始HTML API。我把它做以下工作,

型號:

[Display(Name = "When was that document issued ?")] 
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")] 
public DateTime? LiquorLicenceDocumentIssueDate { get; set; } 

查看:

 <div id="IsLiquorLicenceDocumentOnPremisesYes" class="groupLongLabel"> 
      @Html.LabelFor(m => m.LiquorLicenceDocumentIssueDate) 
      <span class="indicator"></span> 
      @Html.EditorFor(m => m.LiquorLicenceDocumentIssueDate) 
      <span id="validEmail"></span> 
      <br /> 
      @Html.ValidationMessageFor(m => m.LiquorLicenceDocumentIssueDate) 
     </div> 

輸出: 30/12/2011

相關鏈接:

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.applyformatineditmode.aspx

3

對於Razor將文件DateTime.cshtml放入Views/Shared/EditorTemplates文件夾中。 DateTime.cshtml包含兩行並生成格式爲9/11/2001的日期的TextBox。

@model DateTime? 
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" }) 
18

試試這個在MVC 4.0

@Html.TextBoxFor(m => m.YourDate, "{0:dd/MM/yyyy}", new { @class = "datefield form-control", @placeholder = "Enter start date..." }) 
2

下面的代碼將幫助你存在可以在這裏找到不同的日期格式說明的

@Html.Label(@item.Date.Value.ToString("dd - M - yy"))