簡體   English   中英

試圖合成DateTime? 變量導致“方法ToString沒有重載需要1個參數錯誤”

[英]Trying to formate DateTime? variable causes “No overload for method ToString takes 1 argument error”

我正在構建一個ViewModel並在其中我試圖格式化MMMM dd, yyyy格式的DateTime但它拋出錯誤

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.";
            }
        }
    }
}

您必須使用Nullable<DateTime>.Value因為那是DateTime

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

您應該使用Value propery來獲取Nullable<DateTime>的值

如果已為當前Nullable<T>對象分配了有效的基礎值,則獲取該值。

這里是LINQPad的一個例子;

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

輸出將是;

January 14, 2014

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM