user1043963
user1043963

Reputation: 87

C# DateTime.TryParseExact when reading string of date from Excel

I'm trying to read a list of string from excel and parse it to a date.

I specified the format of the string in excel was d/M/yyyy but sometimes I got the string in the format dd/MM/yyyy, d/MM/yyyy, d/M/yyyy HH:mm:ss, dd/M/yyyy h:m:ss, ........ etc.

I don't care what the time is and I only want to get the string of date and parse it to a date. Do I need to define a huge array to contain all the combination of format of date and time before calling TryParseExact? or is there any smart way to do so?

Upvotes: 1

Views: 640

Answers (2)

Fratyx
Fratyx

Reputation: 5797

You could Regex to rearrange the date string to M/d/y which can be parsed easily:

DateTime dt = DateTime.Parse(Regex.Replace(inputStr, @"(\d+)/(\d+)/(\d+)(.*)", @"$2/$1/$3"), CultureInfo.InvariantCulture);

Upvotes: 2

Jacob Lambert
Jacob Lambert

Reputation: 7679

Your best option is going to be to ensure that the data from excel is in the format you want, but you can split up the date string, and make a Date object from the resulting arrays:

var datePart = (excelString.Split(' '))[0];
var dateParts = datePart.Split('/');
DateTime finalDate = new DateTime(Int32.Parse(dateParts[2]), Int32.Parse(dateParts[1]), Int32.Parse(dateParts[0]));

While this will work, since it is hard-coded, it will break if the format of dd/mm/yyyy ever changes to say yyyy-mm-dd.

Upvotes: 1

Related Questions