Reputation: 11366
What is the easiest way to convert the following date created using
dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture)
into a proper DateTime
object?
20090530123001
I have tried Convert.ToDateTime(...)
but got a FormatException
.
Upvotes: 26
Views: 27947
Reputation: 351626
Try this:
DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
If the string may not be in the correct format (and you wish to avoid an exception) you can use the DateTime.TryParseExact
method like this:
DateTime dateTime;
DateTime.TryParseExact(str, "yyyyMMddHHmmss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
Upvotes: 41
Reputation: 882481
Good tutorial here -- I think you just want Parse, or ParseExact with the right format string!
Upvotes: 3
Reputation: 36035
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
var date = DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)
Upvotes: 4