-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

1
  • 3
    The second parameter of ParseExact (the format) could be also an array of formats Commented Oct 5, 2017 at 15:16

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

and will it apply them in order, or it will chose the best match ?
@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
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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.