简体   繁体   中英

C# make DateTime.TryParse() NOT assume year

The DateTime.TryParse() method in C# will assume current year if there's no year specified. I want a function that will return false if the year is not specified (and not assume).

I cannot use DateTime.TryParseExact() because I don't know the format - I want it to work in general just like DateTime.TryParse() .

These test cases should return false :

"3/15"
"Dec 16,"
"4-11"
"Thursday Aug 6"
"Sept-9"

These test cases should return true :

"11/22/2016"
"Wed Jan 1, 2021"
"9-2-16"
"Aug.5.2018"
"2.28.1996"

You cannot parse unknown date format. The TryParseExact is trying to parse a string to DateTime with exact format. I would suggest you to work with different formats you have specified like this

using System.Globalization;

var formats = new[] {"MM/dd/yyyy", "ddd MMM d, yyyy", "M-d-yy", "MMM.d.yyyy", "MM.dd.yyyy", "M.d.yyyy"};
foreach(var format in formats)
{
     bool isValidDateTime = DateTime.TryParseExact(dateText, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out value);
     if (isValidDateTime) 
     {
        break;
     }
}

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