我在 MSDN 中找到了一个字符串到日期时间转换的示例。但是不行,掉进catch()。为什么这个代码块不起作用?
DateTime dateValue;
string dateString = "2/16/2008 12:15:12 PM";
try {
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
最佳答案
您使用的是当前文化中日期/时间格式的任何概念 - 我猜您所处的文化通常是日早于月。
如果您知道格式,我通常会使用不变文化和 TryParseExact
- 绝对不要使用Parse
和一个 catch堵塞;要么使用 TryParseExact
或 TryParse
.在这种情况下:
if (DateTime.TryParseExact(dateString, "M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture, 0, out dateValue))
{
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
else
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
如果您不知道输入格式,但您知道要使用的区域性,我会使用具有适当区域性的DateTime.TryParse
。
关于c# - 字符串到日期时间无法转换 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9953830/