-3

Well I"m trying to read a csv file in my directory but it has a DateTime value. The thing is I'm trying to read the value but shows me this error:

String was not recognized as a valid Datetime

this is the library from where im calling the value 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();
    }
}

And this is where it gives me the error:

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();

}
Grant Winney
  • 61,140
  • 9
  • 100
  • 152
SoyPoko
  • 1
  • 1
  • Use DateTime.Parse with FormatProvider overload option.it is most likely format mismatch in DateTime string. – Nauty Sep 17 '19 at 18:00
  • The error is fairly self-explanatory. We cannot see your data, but it's clear that `values[r, 3]` does not contain a string that `DateTime` knows how to parse. If you know how to parse it, you can use `DateTime.ParseExact` and pass in the format string that tells `DateTime` how to parse the string. – Rufus L Sep 17 '19 at 18:44

1 Answers1

0

Try to do this

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));