【问题标题】:Cannot convert type 'string' to 'System.DateTime'无法将类型“字符串”转换为“System.DateTime”
【发布时间】:2009-04-21 15:46:26
【问题描述】:

尝试执行以下操作:

order.ExpirationDate =(DateTime) ( ExpMonth + "/" + ExpYear);

ExpMonth、Expyear 都是整数。

【问题讨论】:

    标签: c# .net datetime


    【解决方案1】:

    这对你会更好:

    order.ExpirationDate = new DateTime(ExpYear, ExpMonth, 1)
    

    【讨论】:

      【解决方案2】:

      你需要使用:

      DateTime.Parse(ExpMonth.ToString() + "/" + ExpYear.ToString());
      

      【讨论】:

        【解决方案3】:

        试试这个:

        DateTime dt;
        if (DateTime.TryParse(ExpMonth + "/" + ExpYear, out dt))
        {
           // success
        }
        

        【讨论】:

          【解决方案4】:

          尝试使用将月份和年份作为参数的构造函数创建一个新的 DateTime(它也需要一天,但您可以默认为 1)而不是强制转换字符串,这样更简洁。

          【讨论】:

            猜你喜欢
            • 2011-05-28
            • 2023-03-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-06-22
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多