【问题标题】:C# DateTime Parsing - inconsistent formatC# DateTime 解析 - 格式不一致
【发布时间】:2018-12-04 22:54:13
【问题描述】:

我有一个示例日期/时间字符串,我需要将其转换为 datetimeoffset。

有一个巨大的不一致 - 如果一个月中的日期

例如:'Tue Dec 4 22:39:38 UTC 2018''Tue Dec 14 22:39:38 UTC 2018'

我目前使用 DateTimeOffset.ParseExact(dateTime, "ddd MMM dd HH:mm:ss UTC yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) 解析它,对于日期为

FormatException: String 'Tue Dec  4 22:52:42 UTC 2018' was not recognized as a valid DateTime.

我知道我可以用单个空格搜索和替换双空格字符,但是有没有更优雅的方法可以使用格式字符串来实现这一点?

【问题讨论】:

  • I know I can search and replace double space character with a single space, but is there a more elegant way to achieve this using the format string? 这就是我的建议。它简单易懂。
  • 感谢您的回复!我只是想知道字符串格式中是否存在某种通配符,或者 .NET 中是否存在更灵活的日期解析库?
  • 您是否尝试过使用DateTimeStyles.AllowLeadingWhite 标志?
  • DateTimeStyles.AllowInnerWhite
  • 太棒了,DateTimeStyles.AllowInnerWhite 成功了!谢谢大家!

标签: c# datetime datetime-format


【解决方案1】:

这个问题似乎有几个问题(包括我自己关于使用AllowLeadingWhite 的错误问题(我的意思是AllowInnerWhite)。

但是,仅将AllowInnerWhite 与现有格式字符串一起使用仍然会产生错误:

Console.WriteLine(DateTimeOffset.ParseExact("Tue Dec  4 22:39:38 UTC 2018", "ddd MMM dd HH:mm:ss UTC yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowInnerWhite));

生产:

FormatException:字符串未被识别为有效的 DateTime。

但是,从不同的角度来看,为什么不更改日期格式本身以允许使用单位数日期。使用"ddd MMM d HH:mm:ss UTC yyyy"(实际日期使用单个“d”而不是“dd”):

Console.WriteLine(DateTimeOffset.ParseExact("Tue Dec  4 22:39:38 UTC 2018", "ddd MMM d HH:mm:ss UTC yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowInnerWhite));
Console.WriteLine(DateTimeOffset.ParseExact("Tue Dec 11 22:39:38 UTC 2018", "ddd MMM d HH:mm:ss UTC yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowInnerWhite));
Console.WriteLine(DateTimeOffset.ParseExact("Fri Dec 14 22:39:38 UTC 2018", "ddd MMM d HH:mm:ss UTC yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowInnerWhite));

请注意,'Tue Dec 14 22:39:38 UTC 2018' 的示例数据将失败,因为 2018 年 12 月 14 日是星期五,而不是星期二。

【讨论】:

    【解决方案2】:

    这就是 DateTimeStyles.Allow* 标志的用途:它们指示解析器忽略日期字符串中的空格。

    在您的情况下,字符串以缩写的工作日名称开头,因此在一位数的日期编号的情况下,足以忽略额外空格的标志是

    DateTimeStyles.AllowInnerWhite
    

    此处记录了此标志和相关标志:https://docs.microsoft.com/en-us/dotnet/api/system.globalization.datetimestyles?view=netframework-4.7.2

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多