c# - 无法将类型 'string' 隐式转换为 'System.DateTime' ,无法转换特定列的数据类型

标签 c# asp.net datetime

我是 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/

相关文章:

c# - 从 .NET C# 运行 Gulp 任务?

c# - C#中如何自定义Resharper的 "code clean up"改变文档头规则

asp.net - BaseController 在 MVC 中的用途是什么?

asp.net - 在 Windows 2008 服务器上运行 aspnet_setreg.exe

asp.net - 横幅宽度不受浏览器大小限制

PHP 持续时间下拉列表

sql-server - 以下 SQL Server 声明 : datetime2(7)? 的含义是什么

c# - HttpClient 重定向后不发送基本身份验证

c# - 如何获得进程所有者的用户名?

postgresql - 从 PSQL 中的字符串中提取年和周数时出现问题