【问题标题】:cannot convert string to datetime using ParseExact无法使用 ParseExact 将字符串转换为日期时间
【发布时间】:2014-11-04 14:29:44
【问题描述】:

我的 XML 配置数据文件中有这样的字符串(以 12 小时制):

expires="10/27/2014 2:42:57 PM"

我想将该值分配为这样的类的(日期时间)成员:

 Common.SOExpiries = 
     DateTime.ParseExact(gSet.Attribute("expires").Value, "MM/dd/yyyy hh:mm:ss",    
     CultureInfo.InvariantCulture);

但我收到错误“字符串未被识别为有效日期时间”

我在这里做错了什么?

顺便说一句,这是在英国,所以 CultureInfo 应该没问题

【问题讨论】:

  • “hh:mm:ss”不理解“PM”使用“hh:mm:ss tt”
  • 为什么在众神绿地上有人对这个问题评分!?!?
  • 我猜要么是我的名誉在我之前,要么(更有可能)看起来我没有做足够的研究来找出问题所在......这是不是这样的,我做了研究,但没有得到关于 12 小时制的部分!

标签: c# .net datetime cultureinfo


【解决方案1】:

应该是:

"MM/dd/yyyy h:mm:ss tt"

因为您忘记了 tt 表示 AM/PM 和 h,因为您有 1-12 小时,而不是 01-12 小时格式。考虑一下您的秒数和分钟数是否也应该是sm

【讨论】:

  • 即使我这样做,它仍然会抛出同样的错误:Convert.ToDateTime(DateTime.ParseExact(gSet.Attribute("expires").Value, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture));
【解决方案2】:

您还需要解析 AM / PM 部分。

Common.SOExpiries = 
 DateTime.ParseExact(gSet.Attribute("expires").Value, "MM/dd/yyyy hh:mm:ss tt",    
 CultureInfo.InvariantCulture);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多