-2

I am working on building a console application which read a .csv file and add the values to the database. now i have some CSV columns which store date time values. But those column sometimes contain the datatime with seconds while sometimes it does not. here is a sample of some data for the date field:-

03/30/2016 10:55:49
04/01/2016 11:02

now when i try to parse the above string into a date-time as follow:-

formattedDateCreated = DateTime.ParseExact(fields[DateCreatedIndex], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

i will get the following exception when i try to parse the second date :-

String was not recognized as a valid DateTime

so can anyone advice on this please? how i can make my Parse more dynamic to work on date formats with seconds or without seconds?? Thanks

John John
  • 1
  • 72
  • 238
  • 501

2 Answers2

3

You can use the overload that supports multiple formats:

string[] formats = {"MM/dd/yyyy HH:mm:ss", "MM/dd/yyyy HH:mm" };
DateTime formattedDateCreated = DateTime.ParseExact(fields[DateCreatedIndex], formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • and will it apply them in order, or it will chose the best match ? – John John Oct 05 '17 at 15:22
  • 1
    @johnG: first match wins, so i would use default format first and better avoid formats like `MM/dd` + `dd/MM`, otherwise you might get no exception but an incorrect `DateTime`. If you want to see the [source](http://referencesource.microsoft.com/#mscorlib/system/globalization/datetimeparse.cs,4279d8830fc9e88f,references) – Tim Schmelter Oct 05 '17 at 15:23
2

DateTime.ParseExact can also takes multiple formats:

var formats = new []
{
    "MM/dd/yyyy HH:mm:ss",
    "MM/dd/yyyy HH:mm"
};
var dates = "03/30/2016 10:55:49;04/01/2016 11:02".Split(';')
    .Select(x => DateTime.ParseExact(x, formats, CultureInfo.InvariantCulture, DateTimeStyles.None));
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44