mando100
mando100

Reputation: 49

TryParse a String Number to DateTime return True

This line of code returns true and time is equal to "01/02/2016":

DateTime time;
bool result = DateTime.TryParse("1,2", CultureInfo.CurrentCulture, DateTimeStyles.None, out time);

What can I do to return false?

I don't use DateTime.TryParseExact because I would have to specify a format like "YY/MM/DD", but I need to use the default format on the PC.

Upvotes: 0

Views: 1695

Answers (2)

Robert Harvey
Robert Harvey

Reputation: 180868

For what you're trying to do, you're probably better off using TryParseExact. Instead of making arbitrary assumptions about the string you're parsing, it will return false unless the string matches exactly the pattern you want.

According to this, you should be able to specify a culture, and "d" as the format string indicating a "short date". TryParseExact should follow suit and use the formatting specified in the culture you provided for short dates.

Upvotes: 3

Dan Field
Dan Field

Reputation: 21661

If you can live with a standard date format, you should go for DateTime.TryParseExact with one of those qualifiers (in your case, there's a chance "d" might work). Otherwise, you'll need a custom function around DateTime.TryParse.

DateTime.TryParse will try to be helpful by ignoring some missing data and filling in some missing data where it can (see MSDN). If you want to parse it using the current culture, but you still want to exclude certain strings that TryParse would take as valid, you should exclude them before running try parse. For example

public bool MyTryParse(string dateString, out DateTime dt)
{
    dt = new DateTime();
    if (dateString == null)
        return false;


    if (dateString.Length > 3)
            return false;

    return DateTime.TryParse(dateString, CultureInfo.CurrentCulture, DateTimeStyles.None, out dt);            
}

You can add any additional special case tests you want. Note that TryParseExact is likely not what you want here, unless you can use a standard date format as the specified format string (any custom one will override what the CurrentCulture might dictate); compare for example the output of the following:

DateTime dt;
bool res = DateTime.TryParseExact("02/03/2001", "MM/dd/yyyy", CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out dt);
Console.WriteLine(dt);
// will output Feb 3, 2001, but a user in GB would probably intend Mar 3, 2001

bool res = DateTime.TryParseExact("02/03/2001", "d", CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out dt);
Console.WriteLine(dt);
// will output Mar 3, 2001, but might be too restrictive for what you want?
res = DateTime.TryParse("02/03/2001", CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out dt);
Console.WriteLine(dt);
// will output Mar 2, 2001, but goes back to your original problem

Upvotes: 0

Related Questions