2012-07-26 90 views
4

日期在C#中,我解析从字符串的日期,但它给了我错误C#,解析从字符串错误

DateTime.Parse("07/26/2012"); 

错误

System.FormatException: String was not recognized as a valid DateTime. 
    at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) 
    at System.DateTime.Parse(String s) 

是它涉及到日期格式?它与我的电脑设置有关吗?

感谢

+0

尝试'DateTime.Parse(“26/07/2012”)',你可以说它是一个文化问题。 – Jodrell 2012-07-26 14:00:36

+0

我认为这可能与您当前的当前文化设置有关 – jose 2012-07-26 14:00:54

+0

是的,我认为您的系统设置为日期格式不是'mm/dd/yyyy'格式的区域设置。 – Bridge 2012-07-26 14:01:12

回答

9

默认情况下,Parse使用您当前的文化。 ParseExact允许您手动指定日期格式。

试试这个:

DateTime date = DateTime.ParseExact("07/26/2012", "MM/dd/yyyy", CultureInfo.InvariantCulture); 

InvariantCulture选项允许你忽略系统当前区域性设置。

0

使用ParseExact方法:http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

string dateString = "Mon 16 Jun 8:30 AM 2008"; // Modified from MSDN 
string format = "ddd dd MMM h:mm tt yyyy"; 

DateTime dateTime = DateTime.ParseExact(dateString, format, 
    CultureInfo.InvariantCulture); 
+1

ParseExact是一种方法,而不是一个类。 – Polynomial 2012-07-26 14:00:33

+0

是的,当然。我的错... – Nickon 2012-07-26 14:01:43

5

也许您正在运行的文化与此日期格式不兼容。你可以使用InvariantCulture

DateTime.Parse("07/26/2012", CultureInfo.InvariantCulture); 

记住Parse方法使用当前线程的文化。