简体   繁体   English

试图合成DateTime? 变量导致“方法ToString没有重载需要1个参数错误”

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

I am building out a ViewModel and in it I am trying to format a DateTime in MMMM dd, yyyy format but it is throwing the error 我正在构建一个ViewModel并在其中我试图格式化MMMM dd, yyyy格式的DateTime但它抛出错误

No overload for method 'ToString' takes 1 argument

I used http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx to come up with the code 我使用http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx来提出代码

DateUpdated.ToString("MMMM dd, yyyy")

but that is apparently wrong. 但那显然是错的。 What is the correct way to format the date? 格式化日期的正确方法是什么?

ViewModel: 视图模型:

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");

You should use Value propery for getting the value of Nullable<DateTime> 您应该使用Value propery来获取Nullable<DateTime>的值

Gets the value of the current Nullable<T> object if it has been assigned a valid underlying value. 如果已为当前Nullable<T>对象分配了有效的基础值,则获取该值。

Here an example in LINQPad ; 这里是LINQPad的一个例子;

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

Output will be; 输出将是;

January 14, 2014

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM