【问题标题】:Giving System.FormatException: String was not recognized as a valid DateTime. using datetime.ParseExact in C#给出 System.FormatException:字符串未被识别为有效的 DateTime。在 C# 中使用 datetime.ParseExact
【发布时间】:2011-02-16 15:02:25
【问题描述】:

我在 c# 中的代码下方,我将我的字符串类型格式日期转换为日期时间,但给出了错误。

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 = "-";
}

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

请提出问题所在。

谢谢。

【问题讨论】:

    标签: c# .net datetime formatexception


    【解决方案1】:

    您描述的示例日期 (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);
    

    请注意使用 HH(24 小时制)而不是 hh(12 小时制),并使用 InvariantCulture,因为某些文化使用斜线以外的分隔符。

    例如,如果文化是 de-DE,则格式“dd/MM/yyyy”将期望句点作为分隔符 (31.01.2011)。

    【讨论】:

      【解决方案2】:

      可能是因为 mmm(没有这样的月份格式),请尝试 MMM 代替。(看起来像二月/一月/等)

      【讨论】:

      • 不,这不会是问题,好像我只是使用“d”一样也会给出错误,请建议!
      【解决方案3】:

      您使用了错误的格式来解析日期。正确的是:

      DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "dd/MM/yyyy hh:mm:ss", null)
      

      另外,如果您的系统日期格式设置为dd/MM/yyyy,您可以简单地使用:

      DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "G", null)
      

      【讨论】:

      • 我已经尝试过了,但仍然给我同样的错误,请建议!
      【解决方案4】:

      试试 DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "g", null);

      或在这里查看:http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-29
        • 1970-01-01
        相关资源
        最近更新 更多