2014-01-14 35 views
2

我建立了一個ViewModel,並在其中我想在MMMM dd, yyyy格式來格式化DateTime但它引發錯誤試圖合成DateTime?變量會導致「不超載的方法ToString需要1個參數錯誤」

No overload for method 'ToString' takes 1 argument 

我用http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx拿出代碼

DateUpdated.ToString("MMMM dd, yyyy")

但這顯然是錯誤的。什麼是格式化日期的正確方法?

視圖模型:

public class ConversionFactorsVM 
{ 
    [Required] 
    public int TankID { get; set; } 

    [ReadOnly(true), DisplayName("Product Name")] 
    public string ProductName { get; set; } 

    [ReadOnly(true), DisplayName("Product ID")] 
    public int Productnumber { get; set; } 

    [Required, Range(0, 200.9, ErrorMessage = "Gravity must be between 0 and 200.9")] 
    public decimal Gravity { get; set; } 

    [Required, Range(0, 200.9, ErrorMessage = "Temperature must be between 0 and 200.9")] 
    public decimal Temperature { get; set; } 

    [ReadOnly(true)] 
    public decimal Factor { get; set; } 

    public DateTime? DateUpdated { get; set; } 

    [DisplayName("Last Updated")] 
    public string LastUpdate 
    { 
     get 
     { 
      if (DateUpdated.HasValue) 
      { 
       return DateUpdated.ToString("MMMM dd, yyyy"); 
      } 
      else 
      { 
       return "Never Updated."; 
      } 
     } 
    } 
} 

回答

11

你必須使用,因爲這Nullable<DateTime>.Value年代DateTime

return DateUpdated.Value.ToString("MMMM dd, yyyy"); 
+0

感謝那些完美。一旦SO讓我回答,就會標記爲答案。 – Matthew

0

您應該使用Value屬性格式爲獲得的Nullable<DateTime>

值獲取的值目前的Nullable<T>對象是否已被 分配了有效的基礎值。

這裏的一個例子在LINQPad;

DateTime? DateUpdated = DateTime.Now; 
DateUpdated.Value.ToString("MMMM dd, yyyy").Dump(); 

輸出將;

January 14, 2014 
相關問題