Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tryparse datetime string to datetime format [duplicate]

Tags:

c#

datetime

I am trying to parse "31.01.2017 07:56:29.470000000"date time string into datetime format.

Code used:

   DateTime requiredDate;
    string date = "31.01.2017 07:56:29.470000000";

    DateTime.TryParseExact(date,
                           "dd.MM.yyyy hh:mm:ss.fffffff",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out requiredDate);

NOTE: date string is exact "31.01.2017 07:56:29.470000000", however if I use "31.01.2017 07:56:29.4700000" then it is working fine.

Please parse "31.01.2017 07:56:29.470000000".

like image 792
Gaurav123 Avatar asked Mar 08 '23 08:03

Gaurav123


2 Answers

The problem lies in the maximum allowed number of fs in your parse string: The maximum value is fffffff (7 fractions). Your string contains 9 of them.

You can find this limitation in the documentation. It mentions all possible values between f and fffffff, but not further.

like image 173
Patrick Hofman Avatar answered Mar 16 '23 22:03

Patrick Hofman


The problem is in the number of f which as a maximum of 7. You are using the Round-trip date/time pattern that complies with ISO 8601. Please see the documentation.

The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values.

As you can see, there are only 7 digits of f in the format indicated by the documentation.

To solve your problem you should remove the last 2 digit from your input.

like image 43
Omar Muscatello Avatar answered Mar 16 '23 21:03

Omar Muscatello