0

I am working on c# application, which reads data from a .csv file and populate our database.

now the .csv file contain the date information in the following format dd/mm/yyyy such as 22/07/2011. so when I try adding this value inside our database using ado.net entity framework :-

TextFieldParser parser = new TextFieldParser(@"C:\csv\file01.csv");

parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");


while (!parser.EndOfData)
{
    Employee DBrecord = new Employee();
    DBrecord.LeavingDate = DateTime.Parse(CSVfields[49]);

I got the following exception :-

String was not recognized as a valid DateTime.

so can anyone advice on this please , how I can add my date with the following format dd/mm/yyyy inside the database ?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

1 Answers1

1

Try DateTime.ParseExact():

var result = DateTime.ParseExact(
    dateString,
    "dd/MM/yyyy",
    CultureInfo.InvariantCulture
);

This basically tells the parser what format to expect.

Note that it's MM and not mm as one is months, the other is minutes.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
  • thanks for the reply,, but in my case the CSVfield[49] might be empty,, so the ParseExact will raise an exception ... do I need to check if the string is empty before calling ParseExact() ? or I can handle this without the check ? –  Apr 04 '16 at 15:46
  • Yes you'd have to check if it's empty. – Lloyd Apr 04 '16 at 15:46