H. Meiser
H. Meiser

Reputation: 11

Converting a string to date in c#

from a file i read a string like this: "Nov 4 07:27:27 2022 GMT". I try to convert this to german Datetime, later it will be stored in a SQL-table. Currently i do the conversion like this:

MyTmpString = "Nov  4 07:27:27 2022 GMT";
string format;
CultureInfo provider = CultureInfo.InvariantCulture;
format = "MMM  d HH:mm:ss yyyy GMT";
try {
    Datum_von = DateTime.ParseExact(MyTmpString, format, provider);
    Console.WriteLine("{0} converts to {1}.", MyTmpString, Datum_von.ToString());
}
catch (FormatException) {
    Console.WriteLine("{0} is not in the correct format.", MyTmpString);
}

This works for that specific case. I already run into problems if day as more than 1 digit. In this case i have to use a format like this:

format = "MMM dd HH:mm:ss yyyy GMT";

May be the string occurs in more variants currently i dont know. i dont want to create a format and try-catch for every possibility. Iam looking for a kind of universal conversionmethod to have a german date at the end. What should i do here, do you have any recommendations?

Thank you, Hans

Upvotes: 0

Views: 98

Answers (1)

Palle Due
Palle Due

Reputation: 6312

As Hans Kesting suggests, ParseExact's -d format shouldn't care if days are 1 or 2 digits. Your problem is the extra spaces. Also instead of relying on catching an exception, which is expensive performance-wise, you should use TryParseExact. It even has an option that allows you to ignore superfluous white space in the string:

var myTmpString = "Nov    14    07:27:27   2022 GMT";
// Or var myTmpString = "Nov    4    07:27:27   2022 GMT";

System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
string format = "MMM d HH:mm:ss yyyy GMT";
bool result = DateTime.TryParseExact(myTmpString, format, provider, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out DateTime datum_von);
if (result)
{
    Console.WriteLine("{0} converts to {1}.", myTmpString, datum_von.ToString());
}
else
{
    Console.WriteLine("{0} is not in the correct format.", myTmpString);
}

If TryParseExact returns true, you can use the value from the out parameter, otherwise parsing has failed.

Upvotes: 2

Related Questions