gpt4 book ai didi

c# - DateTime.TryParse 如何知道日期格式?

转载 作者:太空狗 更新时间:2023-10-30 01:16:11 26 4
gpt4 key购买 nike

这是一个场景。

  • 您有一个表示日期的字符串,即“Jan 25 2016 10:10 AM”。
  • 您想知道它是否代表特定文化中的日期。
  • 您想知道什么日期时间模式满足这个日期字符串。

例子:

  • 日期字符串是“2016 年 1 月 25 日上午 10:10”
  • 文化是 en-US
  • 它的可能格式可以是“MMM dd yyyy HH:mm tt”

实现:

  • 要获取所有日期时间模式的列表,您可以获取 CultureInfo.DateTimeFormat.GetAllDateTimePatterns()
  • 然后尝试重载版本的DateTime.TryParseExact(dateString, pattern, culture, DateTimeStyles.None, out resultingDate)对于上面的每个模式,看看它是否可以解析日期。
  • 这应该会为您提供所需的日期时间模式。

但是如果我们迭代所有这些模式,它将找不到任何匹配项!

如果你尝试使用 DateTime.TryParse(dateString, culture, DateTimeStyles.None, out resultingDate) 会更奇怪并且它确实解析了正确的日期!

所以问题是 DateTime.TryParse 是怎么来的?当此信息不是 CultureInfo 的一部分时,知道日期字符串的模式以及如何在一种文化中获取这些信息?

谢谢!

最佳答案

我同意 xanatos,对此没有完美解决方案,您不能假设每个格式GetAllDateTimePatterns 返回值可以用 ParseTryParse 方法完美解析。

来自 DateTimeFormatInfo.GetAllDateTimePatterns ;

You can use the custom format strings in the array returned by the GetAllDateTimePatterns method in formatting operations. However, if you do, the string representation of a date and time value returned in that formatting operation cannot always be parsed successfully by the Parse and TryParse methods. Therefore, you cannot assume that the custom format strings returned by the GetAllDateTimePatterns method can be used to round-trip date and time values.

如果您看到 Remarks section页面上,GetAllDateTimePatterns方法返回的96种格式中,TryParse方法可以解析的格式只有42种,it-IT culture for例子.7

Tarek Mahmoud Sayed 回应为;

Parse/TryParse are implemented as finite state machine so it doesn’t really use the date patterns in parsing. It just split the parsed string into tokens and try to find if the token match specific part of the date (like Month, day, day of week…etc.). in the other hand ParseExact/TryParseExact will just parse the string according to the passed format pattern.

关于c# - DateTime.TryParse 如何知道日期格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36058319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com