将字符串转换为日期时间MVC4

时间:2013-06-27 10:25:02

标签: c#-4.0 asp.net-mvc-4

这个问题看起来不太明显,但我几乎找不到相关的建议。

我的日期和时间如下所示:

string s = "Fri Jun 28 2013 00:00:00 GMT+0530 (India Standard Time)";
DateTime from = Convert.ToDateTime(s).ToUniversalTime();

但这引发了异常:

{System.SystemException}: {"String was not recognized as a valid DateTime."}

有人可以建议我该如何处理?

1 个答案:

答案 0 :(得分:4)

您可以使用TryParseExact方法:

string s = "Fri Jun 28 2013 00:00:00 GMT+0530 (India Standard Time)";
DateTime date;
if (DateTime.TryParseExact(s, "ddd MMM dd yyyy hh:mm:ss 'GMT'zzz '(India Standard Time)'", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
    // You could use the date here
}
else
{
    // The string was not in the correct format
}