【问题标题】:Cannot implicitly convert type 'string' to 'System.DateTime', convert datatype for a specific column无法将类型“字符串”隐式转换为“System.DateTime”,转换特定列的数据类型
【发布时间】:2014-02-20 02:22:03
【问题描述】:

我是 ASP.NET 和 C# 的新手。 我想知道如何将一个字段从字符串转换为 DataTime。

string[] Lines = File.ReadAllLines(fileName);
string[] Fields;

//Remove Header line
Lines = Lines.Skip(1).ToArray();
List<CountTable> emList = new List<CountTable>();
foreach (var line in Lines)
{
    Fields = line.Split(new char[] { ',' });
    emList.Add(
        new CountTable
        {
            CountID = Fields[0].Replace("\"", ""),
            Date = Fields[1].Replace("\"", ""),
            UserID = Fields[2].Replace("\"", ""),
            PrinterID = Fields[3].Replace("\"", ""),
            Color = Fields[4].Replace("\"", ""),
            BW = Fields[5].Replace("\"", ""),
        });
}

我收到了这个错误

无法将类型“字符串”隐式转换为“System.DateTime”

在这一行

Date = Fields[1].Replace("\"", ""),

谁能帮我解决这个错误的语法。

谢谢!

【问题讨论】:

    标签: c# asp.net datetime


    【解决方案1】:

    您是否尝试将字符串转换为 DateTime 对象?

    见下面的代码:

    string[] Lines = File.ReadAllLines(fileName); string[] Fields;
    //Remove Header line
    Lines = Lines.Skip(1).ToArray();
    List<CountTable> emList = new List<CountTable>();
    foreach (var line in Lines)
    {
        Fields = line.Split(new char[] { ',' });
        emList.Add(
            new CountTable
            {
                CountID = Fields[0].Replace("\"", ""),
                Date = Convert.ToDateTime(Fields[1].Replace("\"", "")),
                UserID = Fields[2].Replace("\"", ""),
                PrinterID = Fields[3].Replace("\"", ""),
                Color = Fields[4].Replace("\"", ""),
                BW = Fields[5].Replace("\"", ""),
            });
    }
    

    【讨论】:

      【解决方案2】:

      string 不能隐式转换为 DateTime。您必须使用DateTime.Parse()string 显式转换为DateTime

      Date = DateTime.Parse(Fields[1].Replace("\"", ""))
      

      【讨论】:

        【解决方案3】:

        您必须将string 显式转换为DateTime。我建议使用DateTime.ParseExact Method。这一行

        Date = Fields[1].Replace("\"", ""),
        

        应该改成这个

        Date = DateTime.ParseExact(Fields[1].Replace("\"", ""), "MM/dd/yyyy", null),
        

        请注意,使用上面的代码,我假设文件中的日期具有MM/dd/yyyy 格式,即02/20/2014。如果它有其他格式,那么您必须将"MM/dd/yyyy" 更改为其他格式。

        【讨论】:

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