[英]String to Datetime can not convert - C#
我在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
与适当的区域性一起使用。
尝试使用ParseExact
传递适当的格式提供程序,如以下示例所示:
string dateString = "2/16/2008 12:15:12 PM";
string format = "M/dd/yyyy hh:mm:ss tt ";
DateTime dateTime = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.