给出System.FormatException:String未被识别为有效的DateTime.在C#中使用datetime.ParseExact

Man*_*ngh 2 .net c# datetime formatexception

我在c#中的代码下面,我将我的字符串类型格式日期转换为datetime,但是给出了错误.

if (!string.IsNullOrEmpty(SessionDictionary.GetValue("UserDetails", "ExpiryDate")))
{
    DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "dd mmm yy", null);                      
    strDate = sitedata.FormatDate(ExpiryDate, TridionDateFormat.ShortDate);
}
else
{
    strDate = "-";
}
Run Code Online (Sandbox Code Playgroud)

SessionDictionary.GetValue("UserDetails", "ExpiryDate")的字符串类型数据返回"31/01/2011 00:00:00"格式日期,在我使用DateTime.ParseExact它的上面的代码中给我System.FormatException: String was not recognized as a valid DateTime.错误.

请说明出了什么问题.

谢谢.

Joe*_*Joe 5

您描述的样本日期(31/01/2011 00:00:00)看起来像格式dd/MM/YYYY HH:mm:ss,那你为什么使用dd mmm yyyy?

尝试

DateTime.ParseExact(..., "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

注意使用HH(24小时制)而不是hh(12小时制),以及使用InvariantCulture,因为有些文化使用除斜线之外的分隔符.

例如,如果文化是de-DE,则格式"dd/MM/yyyy"会将期间视为分隔符(31.01.2011).