2016-06-14 13 views
0

是yyyy DateTime的有效格式嗎?我只想存儲一年。由於mvc模型會拋出yyyy不是datetime的有效格式的錯誤。是否yyyy是DateTime的有效格式C#

[DisplayName("Year Obtained")] 
[DataType(DataType.Date)] 
[DisplayFormat(DataFormatString = "{0:yyyy}", ApplyFormatInEditMode = true)] 
public DateTime reDateFrom { get; set; } 
+3

的http://計算器.com/questions/696506/sql-datatype-how-to-store-a-year回答你的問題:) – Roman

+0

'DisplayFormat'屬性只會影響使用諸如'Html.DisplayFor'等方法的顯示格式,而不會影響數據庫格式。 – DavidG

+0

如何設置數據庫格式的年份? – Ejazkhan

回答

0

你可以在模型中有一兩件事你可以把類型爲int值作爲今年的部分是你所需要的變革型數據庫過於一個整數類型。

,或者你可以把類型的模型,並在控制器中的字符串,而存儲則可以做到這一點

string dateTime = DateTime.UtcNow.ToString("yyyy"); 

只有

0

你要存儲一個int類型將存儲年份部分進入數據庫的一年。

或者,如果你想離開DateTime類型到數據庫中,你可以創建一個模型元數據類MVC,然後創建一個新的詮釋財產「獲得年度」,請參閱以下內容:

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using System.Web; 

namespace YourWebApp.Models 
{ 
    [MetadataType(typeof(YourClassMetaData))] 
    public partial class YourClass 
    { 
     [DisplayName("Year Obtained")] 
     public int YYObtained { 
      get 
      { 
       return this.reDateFrom.Year; 
      } 
     } 
    } 

    public class YourClassMetaData 
    { 
     [DataType(DataType.Date)] 
     public DateTime reDateFrom { get; set; } 
    } 
} 
相關問題