我是 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("\"", ""),
});
}
我收到这个错误
Cannot implicitly convert type 'string' to 'System.DateTime'
在这一行
Date = Fields[1].Replace("\"", ""),
任何人都可以帮我解决语法问题吗?
谢谢!
最佳答案
您是否尝试过将字符串转换为 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("\"", ""),
});
}
关于c# - 无法将类型 'string' 隐式转换为 'System.DateTime' ,无法转换特定列的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896804/