【问题标题】:C# {String was not recognized as a valid Datetime} [duplicate]C# {String 未被识别为有效的日期时间} [重复]
【发布时间】:2019-09-17 17:51:08
【问题描述】:

好吧,我正在尝试读取目录中的 csv 文件,但它有一个 DateTime 值。问题是我正在尝试读取该值,但显示了这个错误:

字符串未被识别为有效的日期时间

这是我调用 DateTime 值的库:

public class Main
{
    string names;
    string addresses;
    string phones;
    DateTime birthdates;

    string resultado = string.Empty;
    RegisterSalesTableAdapter myRegisterSales = new RegisterSalesTableAdapter();



    public string InsertSalesTable(string Name, string Address, string Phone, DateTime Birthdate)
    {

        names = Name;
        addresses = Address;
        phones = Phone;
        birthdates = Birthdate;


        myRegisterSales.Insert(Name, Address, Phone, Birthdate);
        return resultado;
    }

    public string Nombres { get => names; set => names = value; }
    public string Direcciones { get => addresses; set => addresses = value; }
    public string Telefonos { get => phones; set => phones = value; }
    public DateTime Cumpleanos { get => birthdates; set => birthdates = value; }


    public DataTable GetSalesTable()
    {
        return myRegisterSales.GetData();
    }
}

这就是它给我错误的地方:

static List<Main> list;
static void Main(string[] args)
{
    list = new List<Main>();

    // Get the data from path.
    string sampleCSV = @"C:\Borrado\PRUEBA.csv";

    string[,] values = LoadCSV(sampleCSV);
    int num_rows = values.GetUpperBound(0) + 1;

    //Read the data and add to List 
    for (int r = 1; r < num_rows; r++)
    {


        //name age mail company
        Main main = new Main();

        main.InsertSalesTable(values[r, 0], values[r, 1], values[r, 2], DateTime.Parse(values[r, 3]));
    }

    //read data from list
    foreach (var item in list)
    {
        Console.WriteLine(item.Nombres + "\t" + item.Direcciones + "\t" + item.Telefonos + "\t" + item.Cumpleanos + "\t");
    }
    Console.ReadLine();

}

【问题讨论】:

  • 将 DateTime.Parse 与 FormatProvider 重载选项一起使用。这很可能是 DateTime 字符串中的格式不匹配。
  • 这个错误是不言自明的。我们看不到您的数据,但很明显values[r, 3] 不包含DateTime 知道如何解析的字符串。如果您知道如何解析它,您可以使用DateTime.ParseExact 并传入告诉DateTime 如何解析字符串的格式字符串。

标签: c# datetime console string-formatting string-parsing


【解决方案1】:

尝试这样做

string dateString = values[r, 3];
string format = "dd/MM/yyyy HH:mm:ss.ffffff"; /*use the correct format*/
date = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

main.InsertSalesTable(values[r, 0], values[r, 1], values[r, 2], 
DateTime.Parse(date));

【讨论】:

  • "date = DateTime.ParseExact(dateString, format, provider);"当我运行它时,它说“名称提供程序在当前上下文中不存在”
  • 试试,我已经改正了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
相关资源
最近更新 更多