简体   繁体   中英

DateTime.TryParse fails at yyyy only

I have a filter field that allows to search by partial or full date that can be entered in different formats - that is, whichever way the user wants to enter it, so TryParseExact doesn't look like the best option.

The problem is that the following code:

DateTime.TryParse(fromDate.Text, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateFromValue)

parses everything but yyyy strings. Eg "05/1980" and "1980/05" are recognized as {1/05/1980 12:00:00 AM}, but "1980" fails.

I suspect the parser has no way to distinguish between, say, yyyy and ffff when all it gets is a 4-digit sequence, but I still need to get this working. Is there perhaps a more elegant way to do it than

if(!DateTime.TryParse("1980", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
    DateTime.TryParseExact("1980","yyyy",CultureInfo.InvariantCulture, DateTimeStyles.None, out date);

or am I doing it the wrong way altogether?

Thank you in advance!

I think you cannot use DateTime.Parse with just year only, because the month and day are ambiguous. Using DateTime.ParseExact or DateTime.TryParseExact with specific date format works instead.

Your if condition looks wrong to me though, how do you combine the two conditions?

if(!DateTime.TryParse("1980", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
DateTime.TryParseExact("1980","yyyy",CultureInfo.InvariantCulture, DateTimeStyles.None, out date);

should have been:

if(DateTime.TryParse("1980", CultureInfo.InvariantCulture, DateTimeStyles.None, out date) ||
DateTime.TryParseExact("1980","yyyy",CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
// If the first parse success, use that. Otherwise, try to parse the year only with the parseexact.
// Notice the || and the first condition needs to be positive. 

如果要部分匹配,最简单的方法是将日期视为字符串,而只使用字符串匹配而不是依赖日期格式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM