Convert a string to datetime [duplicate]
Possible Duplicate:
How can I convert a string into datetime in .NET?
I have a string in the following format "15/03/2046". how can convert this string to a DateTime object?
My problem is when I do Convert.ToDateTime("15/03/2开发者_运维知识库046") I get an exception.
when I do Convert.ToDateTime("03/03/2046") every thing works fine. so I guess that I have to specify the format somehow while converting....DateTime.Parse
or its sister method DateTime.ParseExact
.
Use DateTime.ParseExact
to specify the format of the input string:
DateTime d = DateTime.ParseExact(
"15/03/2046",
"dd/MM/YYYY",
CultureInfo.InvariantCulture
);
More generic code, using extension method, and default value in case if it can't parse date
void Main()
{
var dt = "15/03/2046";
dt.ToDateTime("fr-FR", DateTime.Now).Dump();
}
public static class Extensions
{
public static DateTime ToDateTime(this string dateTime, string culture, DateTime defaultValue)
{
DateTime dt;
if (DateTime.TryParse(dateTime, System.Globalization.CultureInfo.CreateSpecificCulture(culture), System.Globalization.DateTimeStyles.None, out dt))
return dt;
else
return defaultValue;
}
}
精彩评论