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

标签 c# .net date parsing datetime

这是一个场景。

  • 您有一个表示日期的字符串,即“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/

相关文章:

mysql - 从特定日期选择唯一记录,不包括以前日期的重复记录

c# - HttpContext.User 设置正确,然后被下一个请求丢失/替换

c# - `internal` 和单个项目的 `public` 一样吗?

C# - 使用枚举作为唯一标识符的替代方法

c# - 打开带有 .cs 扩展文件的项目?

java - 按 yyyymmdd 整数计算日差时结果不一致

c# - 在 AxWindowsMediaPlayer 上叠加 Picturebox(或图像)

asp.net - 这个正则表达式是什么意思 : (? ![#$])

c# - 从 MSTest 测试生成可运行的 exe

java - 从 Date() 获取 unix 时间戳