在C#中,我正在从字符串中解析日期,但它给了我错误
DateTime.Parse("07/26/2012");
Run Code Online (Sandbox Code Playgroud)
错误
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)
Run Code Online (Sandbox Code Playgroud)
它与日期格式有关吗?它与我的电脑设置有关吗?
谢谢
默认情况下,Parse使用您当前的文化.ParseExact允许您手动指定日期格式.
试试这个:
DateTime date = DateTime.ParseExact("07/26/2012", "MM/dd/yyyy", CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)
该InvariantCulture选项允许您忽略系统上的当前区域性设置.
也许您运行此文化的文化与此日期格式不兼容.你可以使用InvariantCulture:
DateTime.Parse("07/26/2012", CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)
请记住,该Parse方法使用当前的线程文化.