简体   繁体   中英

DateTime.TryParse converts decimal to datetime

The following line of code return true (which it should not)....and convert 1.0228 into datetime...

DateTime.TryParse(1.0228,out temporaryDateTimeValue)

Somebody please help me.

The following line of code return true (which it should not)....and convert 1.0228 into datetime...

DateTime.TryParse(1.0228,out temporaryDateTimeValue)

This will not compile.

However, if you wrap it in quotes (and clean it up a little bit),

bool success = DateTime.TryParse("1.0228", out temporaryDateTimeValue);

then, yes, you will get true back. You need to read the documentation to understand why, but basically, there are many different ways to format dates and you stumbled on one (maybe M.yyyy ?).

If you don't want it to parse, may I suggest

bool success = DateTime.TryParseExact(
                   "1.0228",
                   "yyyyMMdd", 
                   CultureInfo.InvariantCulture,
                   DateTimeStyles.None,
                   out temporaryDateTimeValue
               );

Then success is false .

I note from the remarks in the documentation :

The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture.

This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000).

Because the DateTime.TryParse(String, DateTime) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results. If a specific date and time format will be parsed across different locales, use the DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) method or one of the overloads of the TryParseExact method and provide a format specifier.

Basically, TryParse "tries" very hard to parse the string you give it (although the " Try " really refers to the fact that the method returns a bool for success/failure indication).

No, that code doesn't return true - it doesn't even compile:

using System;

class Program
{

    static void Main(string[] args)
    {
        DateTime dt;
        Console.WriteLine(DateTime.TryParse(1.0228, out dt));
    }
}

Error:

Test.cs(9,27): error CS1502: The best overloaded method match for
        'System.DateTime.TryParse(string, out System.DateTime)' has some invalid
        arguments
Test.cs(9,45): error CS1503: Argument 1: cannot convert from 'double' to
        'string'

If you change it to "1.0228" it does return true, yes. It looks like it's using a format of "M.yyyy", which is no doubt valid for some cultures... and highlights why it's a bad idea to use DateTime.TryParse in my view. If you've got a specific format (or set of formats) in mind, you should useDateTime.TryParseExact instead so you can specify the format.

I usually find it's a good idea to specify the exact format, and I usually also specify CultureInfo.InvariantCulture unless the date is coming directly from the user (which is rare, in my experience).

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