【问题标题】:Why is this DateTime.ParseExact call failing? [duplicate]为什么这个 DateTime.ParseExact 调用失败? [复制]
【发布时间】:2016-08-27 13:18:52
【问题描述】:
var dateValue = "Mon, 02 May 2016 12:00 PM EDT";
var date = DateTime.ParseExact(
   dateValue,
   "ddd, dd MMM yyyy hh:mm tt K",
   System.Globalization.CultureInfo.InvariantCulture);

据我所知,the official format string documentation 应该可以。相反,它引发了System.FormatException 并带有相当无益的消息:String was not recognized as a valid DateTime.

有什么办法可以找出问题所在?

【问题讨论】:

  • 文档没有提到任何关于 K 接受时区字符串作为输入的内容,所以这可能是你的问题。
  • @SamiKuhmonen,在文档中找到这些句子:More information: The "K" Custom Format Specifier.The "K" Custom Format Specifier。那里有关于K的很好的描述。

标签: c# parsing datetime


【解决方案1】:

这应该可以工作

var dateValue = "Mon, 02 May 2016 12:00 PM EDT".Replace("EDT", "-4");
var date = DateTime.ParseExact(
dateValue,
"ddd, dd MMM yyyy hh:mm tt z",
System.Globalization.CultureInfo.InvariantCulture);

【讨论】:

    【解决方案2】:

    https://msdn.microsoft.com/en-us/library/shx7s921%28v=vs.110%29.aspx 指定 DateTime.Kind 枚举有 3 个成员。因此,也许它不喜欢您将“EDT”指定为一种。

     Member name    Description
     Local          The time represented is local time.
     Unspecified    The time represented is not specified as either local time or Coordinated Universal Time (UTC).
     Utc            The time represented is UTC.
    

    【讨论】:

      【解决方案3】:

      K Custom Format Specifier 不接受时区字符串。

      如果您可以提供小时偏移量而不是字符串,那么您可以使用"z"

      var dateValue = "Mon, 02 May 2016 12:00 PM -4";
      var date = DateTime.ParseExact(
         dateValue,
         "ddd, dd MMM yyyy hh:mm tt z",
         System.Globalization.CultureInfo.InvariantCulture);
      

      【讨论】:

      • 很遗憾,我无法提供小时偏移量。此时间戳字符串按原样来自 Web 服务。但我至少可以用.substring() 切断时区字符串...
      • 真可惜。 Sami 在对您问题的评论中分享的链接可能会有所帮助。
      猜你喜欢
      • 2020-09-13
      • 2012-03-14
      • 1970-01-01
      • 2018-03-02
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 2014-01-16
      相关资源
      最近更新 更多