将字符串转换为DateTime时,字符串未被识别为有效的DateTime [英] String was not recognized as a valid DateTime When Converting String to DateTime
问题描述
问题
我正在尝试将 DateTime
格式的 String
转换为再次将 DateTime
转换为 String
I am trying to convert String
in DateTime
format and again converted DateTime
to String
案例1
string time = "20120718 00:56:03";
DateTime theTime =DateTime.ParseExact(time,"MM-dd-yyyy HH:mm:ss",CultureInfo.InvariantCulture,DateTimeStyles.None);
string convertedTime = theTime.ToString("MM-dd-yyyy HH:mm:ss");
案例2
string time = "20120718 00:56:03";
string CallDate_DBFormat = Convert.ToDateTime(time).ToString("MM-dd-yyyy HH:mm:ss");
DateTime CallTime = Convert.ToDateTime(CallDate_DBFormat);
string convertedTime = CallTime.ToString("MM-dd-yyyy HH:mm:ss");
在两种情况下,我都会得到
In both cases I get the Exception that
字符串未被识别为有效的DateTime
String was not recognized as a valid DateTime
推荐答案
将日期和时间的指定字符串表示形式转换为其使用指定的格式和特定于区域性的等效DateTime格式信息.字符串表示形式的格式必须匹配确切地指定格式.
在您的情况1中,它们不是.改用 yyyyMMdd HH:mm:ss
格式.
In your case #1, they are not. Use yyyyMMdd HH:mm:ss
format instead.
string time = "20120718 00:56:03";
DateTime theTime = DateTime.ParseExact(time,"yyyyMMdd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
string convertedTime = theTime.ToString("MM-dd-yyyy HH:mm:ss");
对于案例2,我们需要了解您的 CurrentCulture
属性.为什么?
For case #2, we need to know your CurrentCulture
property. Why?
因为此方法使用 DateTime.Parse 使用
方法.此处已实现; CurrentCulture
的code>
Because this method uses DateTime.Parse
method with CurrentCulture
. Here how it's implemented;
public static DateTime ToDateTime(String value)
{
if (value == null)
return new DateTime(0);
return DateTime.Parse(value, CultureInfo.CurrentCulture);
}
yyyyMMdd HH:mm:ss
格式不是 CurrentCulture
的标准日期和时间格式,这就是为什么此方法抛出
Probably yyyyMMdd HH:mm:ss
format is not a standard date and time format for your CurrentCulture
and that's why this method throws FormatException
.
这篇关于将字符串转换为DateTime时,字符串未被识别为有效的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!