且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果未指定年份,如何使DateTime.TryParse()失败?

更新时间:2023-11-29 13:42:10

您可以查询文化模式,过滤掉没有一年的文化模式,然后在其余模式上使用 TryParseExact .

You could query for the culture's patterns, filter out those without a year and then use TryParseExact on the remaining patterns.

var allPatterns = culture.DateTimeFormat.GetAllDateTimePatterns();
var patternsWithYear = allPatterns.Where(s => s.Contains("y")).ToArray();
bool success = TryParseExact(input, patternsWithYear, culture, styles, out dateTime);

已知的错误:这没有考虑到转义,您需要用适当的解析替换 Contains("y")调用来解决此问题.

Known bug: This doesn't take escaping into account, you'll need to replace the Contains("y") call with proper parsing to fix this.

或者,如果您对格式限制更严格的话,也可以只使用 LongDatePattern ShortDatePattern .

Alternatively you could go with just LongDatePattern and ShortDatePattern if you're fine with stricter format constraints.