From DateTime.TryParseExact
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly.
In your case, they are not. Use yyyy-MM-dd HH:mm:ss
format instead.
string s = "2014-09-25 09:18:24";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
It is a little bit unclear but if your string is 09/25/2014 09:18:24
, then you can use MM/dd/yyyy HH:mm:ss
format instead. Just a tip, "/"
custom format specifier has a special meaning as replace me with current culture or supplied culture date separator. That means, if your CurrentCulture
or supplied culture's DateSeparator
is not /
, your parsing operation will fail even if your format and string matches exactly.
If you have already a DateTime
and you want to format it, you can use DateTime.ToString(string)
method like;
dt.ToString("yyyy-mm-dd", CultureInfo.InvariantCulture); // 2014-09-25
or
dt.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture); // 2014-09-25 09:18:24
Remember, a DateTime
does not have any implicit format. It just contains date and time values. String representations of them have formats.