简体   繁体   中英

Can't get DateTime.TryParseExact to work

I have the following code:

string[] format = { "yyyy/MM/dd", "MM/dd/yyyy" };
DateTime valueDate;
value = value.Replace("-", "/");
if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueDate))
{
    value = "TO_DATE(" + valueDate + ", 'yyyy-mm-dd')";
}
else
{
    throw new Exception("Could not parse incoming date: " + valueDate);
}

So now I have a test case. And value = '2013/01/21' after the replace statement replacing "-" with "/".

This should match the first format in the format string array. But TryParseExact is not working and always goes to the else path. Can anyone see any errors in this code?

It's not TryParseExact that's the problem, it's the value of your string. I say that because this little scriptcs script:

using System.Globalization;

string[] format = { "yyyy/MM/dd", "MM/dd/yyyy" };
DateTime valueDate;
var value = "2013/01/21";
if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueDate))
{
    Console.WriteLine("Success!");
}
else
{
    Console.WriteLine("Failure!");
}

prints Success! . So, in other words, this statement:

And value = '2013/01/21' after the replace statement replacing "-" with "/".

literally cannot be correct.

As stated by James, it's very possible there is whitespace in the actual string value. There are a couple solutions: remove the whitespace or allow whitespace. To allow whitespace you could use DateTimeStyles.AllowWhiteSpaces rather than DateTimeStyles.None .

Don't know if it's your issue, but make sure you always escape out your forward-slashes when using date formats. A / character is not a literal slash, but rather your local system's date separator (which is usually the forward-slash, but not always).

When using a format string, you escape a forward-slash with a real backslash, like:

DateTime.ParseExact("2012/12/31", "yyyy\\/MM\\/dd", null);
// or
DateTime.ParseExact("2012/12/31", @"yyyy\/MM\/dd", null);

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