Parse C# string to DateTime

Absolutely. Guessing the format from your string, you can use ParseExact

string format = "ddMMyyyyHHmm";

DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);

or TryParseExact:

DateTime dt;
bool success = DateTime.TryParseExact(value, format, 
                     CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

The latter call will simply return false on parse failure, instead of throwing an exception – if you may have bad data which shouldn’t cause the overall task to fail (e.g. it’s user input, and you just want to prompt them) then this is a better call to use.

EDIT: For more details about the format string details, see “Custom Date and Time Format Strings” in MSDN.

Leave a Comment