Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 325
Relativity Avatar asked Jun 28 '11 18:06

Relativity


People also ask

What does datetime TryParse do?

TryParse(String, DateTime)Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

What is decimal TryParse?

TryParse(String, Decimal) Converts the string representation of a number to its Decimal equivalent. A return value indicates whether the conversion succeeded or failed.

How to Convert date string to DateTime?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.


2 Answers

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).

like image 103
jason Avatar answered Sep 30 '22 15:09

jason


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 use DateTime.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).

like image 35
Jon Skeet Avatar answered Sep 30 '22 13:09

Jon Skeet